gpt4 book ai didi

swift - UITextView 绘制不可见/空白字符

转载 作者:搜寻专家 更新时间:2023-10-31 23:00:24 25 4
gpt4 key购买 nike

如何使 UITextView 为制表符、空格和换行符结尾绘制不可见字符?

我认为它必须在 drawRect(CGRect) 方法中或由 Text Kit 中的布局管理器处理。任何简单和/或直观的解决方案?

我只需要知道如何获取每个空白字符的 CGRect 以及哪种覆盖方法可以为每个空白字符无缝绘制图形?

在此先感谢您的任何建议/帮助。
另外,我不介意您是否使用 objective-c 回答,尽管两种语言都是首选。

最佳答案

我找到了一个比将 NSLayoutManagershowsInvisibleCharacters 属性设置为 true 更好的解决方案,方法是继承 NSLayoutManager 和覆盖方法 drawBackgroundForGlyphRange(NSRange, CGPoint),它允许为每个空白字符自定义绘图,例如:

class LayoutManager : NSLayoutManager {

var text: String? { return textStorage?.string }

var font: UIFont = UIFont.systemFontOfSize(UIFont.systemFontSize()) {
didSet {
guard let text = self.text else { return }
let textRange = NSMakeRange(0, (text as NSString).length)
invalidateGlyphsForCharactersInRange(textRange, actualCharacterRange: nil)
invalidateCharacterAttributesForCharactersInRange(textRange, actualCharacterRange: nil)
}
}

override func drawBackgroundForGlyphRange(glyphsToShow: NSRange, atPoint origin: CGPoint) {

super.drawBackgroundForGlyphRange(glyphsToShow, atPoint:origin)

guard let text = self.text else { return }

enumerateLineFragmentsForGlyphRange(glyphsToShow)
{ (rect: CGRect, usedRect: CGRect, textContainer: NSTextContainer, glyphRange: NSRange, stop: UnsafeMutablePointer<ObjCBool>) -> Void in

let characterRange = self.characterRangeForGlyphRange(glyphRange, actualGlyphRange: nil)

// Draw invisible tab space characters

let line = (self.text as NSString).substringWithRange(characterRange)

do {

let expr = try NSRegularExpression(pattern: "\t", options: [])

expr.enumerateMatchesInString(line, options: [.ReportProgress], range: line.range)
{ (result: NSTextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in

if let result = result {

let range = NSMakeRange(result.range.location + characterRange.location, result.range.length)
let characterRect = self.boundingRectForGlyphRange(range, inTextContainer: textContainer)

let symbol = "\u{21E5}"
let attrs = [NSFontAttributeName : Font]
let height = (symbol as NSString).sizeWithAttributes(attrs).height
symbol.drawInRect(CGRectOffset(characterRect, 1.0, height * 0.5, withAttributes: attrs)

}

}

} catch let error as NSError {
print(error.localizedDescription)
}

}

}

}

关于swift - UITextView 绘制不可见/空白字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36666502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com