ios - 如何在 U+FFFC 字符产生的 UITextVIew 中隐藏字符(图标)
问题描述
我正在尝试将自定义(任何)视图附加到 NSAttributedString,我发现并且能够想到的最佳方法是子类化 NSTextAttachment 以创建带有视图的自定义附件,然后自定义 UITextView 类,通过修改 drawGlyphs 方法我可以绘制占位符字符“\u{FFFC}”(我有问题)并在 textView 的顶部添加 subView。除了占位符字符在子视图后面产生“图标”图像 [ currentState ]之外,一切正常,我不知道如何摆脱它(至少隐藏它)。
我从RTViewAttachment带来了这个想法,但是从头开始快速创建,所以我不知道他的解决方案中是否隐藏了适当的答案。
drawGlyphs 方法覆盖
override func drawGlyphs(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) {
super.drawGlyphs(forGlyphRange: glyphsToShow, at: origin)
self.textStorage?.enumerateAttribute(NSAttributedString.Key.attachment, in: glyphsToShow, options: .longestEffectiveRangeNotRequired, using: { val, range, ptr in
if let val = val as? GCIViewAttachment, let container = self.textContainer(forGlyphAt: range.location, effectiveRange: nil) {
var frame = self.boundingRect(forGlyphRange: range, in: container)
frame.origin.x += origin.x
frame.origin.y += origin.y + (frame.size.height - val.attachedView.bounds.size.height)
frame.size = val.attachedView.bounds.size
val.attachedView.frame = frame
}
})
}
处理占位符和视图放置的替换字符
func insertViewHandler(attachment: GCIViewAttachment){
textView.addSubview(attachment.attachedView)
self.textStorage.beginEditing()
self.textStorage.replaceCharacters(in: self.textView.selectedRange, with: "\u{FFFC}")
self.textStorage.addAttributes([.attachment:attachment], range: self.textStorage.editedRange)
let range = NSRange(location: min(self.textStorage.editedRange.location+self.textStorage.editedRange.length, self.textStorage.length), length: 0)
self.textStorage.endEditing()
self.textView.selectedRange = range
}
解决方案
推荐阅读
- c++ - 如何使用函数的输出初始化 const 数组结构字段?
- python - python打印函数中希腊字母的下标问题
- oracle-cloud-infrastructure - Oracle Cloud 始终免费套餐。我有资格吗?
- sql - 无法在 MS Access 的外键字段中插入空值
- python - 尝试将 Dictionary 转换为 DataFrame Pandas 时出现 ValueError
- javascript - 用户输入有时会破坏 REGEX
- sql - Google Big Query:基于当前行条件的聚合新列
- c# - 使用 NoSQL 数据库进行 ASP.NET Core 身份验证
- android - Android Kotlin Coroutine 崩溃,但没有在 Logcat 中报告致命错误
- python-3.x - 我如何计算python文件中的空白行