我想在UITextView中“突出”特定的单词,不是用纯色(通过NSAttributedString就可以了),而是用渐变或者其他一些花哨的效果。
因此,我决定需要手动创建视图,并使用给定文本的边界矩形覆盖(或衬垫)它。
令我惊讶的是,事实证明这是非常简单的。示例位于UIViewController中,txtView是以IBOutlet形式连接的UITextView。
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Converting to NSString as I need a NSRange for glphyRangeForCharacterRange
// (a normal String in Swift returns a Range)
let charRange = (txtView.text as NSString).rangeOfString("dolor sit er elit")
assert(charRange.location != NSNotFound, "Character Range could not be found.")
let glyphRange = txtView.layoutManager.glyphRangeForCharacterRange(charRange,
actualCharacterRange: nil)
let glyphContainer = txtView.layoutManager.textContainerForGlyphAtIndex(glyphRange.location, effectiveRange: nil)
let glyphRect = txtView.layoutManager.boundingRectForGlyphRange(glyphRange,
inTextContainer: glyphContainer!)
let highlightView = UIView(frame: glyphRect)
highlightView.alpha = 0.3
highlightView.backgroundColor = UIColor.redColor()
txtView.addSubview(highlightView)
}可悲的是,这会导致重叠视图(在下面的屏幕截图中是红色的),少了几个点。

它似乎总是以同样的数量减少。这意味着我可能可以硬编码,但这从来不是一个好主意。在模拟器中用各种设备测试了这一点,在iPhone 6上用iOS 8.1.3进行了测试。
我还尝试了其他的变体(通过创建我自己的NSTextContainer等等)受the question on how to get a CGRect for a substring和"boundingRectForGlyphRange does not always work for all strings"的启发
有什么想法(除了resorting to CoreText)吗?
发布于 2015-02-04 22:25:47
尝试通过文本视图的textContainerInset调整字形重排:
var glyphRect = txtView.layoutManager.boundingRectForGlyphRange(glyphRange,
inTextContainer: glyphContainer!)
glyphRect.origin.y += txtView.textContainerInset.top那应该就行了!
https://stackoverflow.com/questions/28330772
复制相似问题