首页 > 解决方案 > 如何在 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
}

标签: iosswiftiphoneuitextview

解决方案


推荐阅读