我想“突出显示” UITextView 中的特定单词,而不是使用纯色(这可以通过NSAttributedString
),而是带有渐变,也许还有一些其他奇特的效果。
因此,我决定有必要手动创建一个视图并使用给定文本的边界矩形覆盖(或底层)它。
令我惊讶的是,事实证明这非常简单。示例位于 UIViewController 内部,txtView
成为一个UITextView
连接为IBOutlet
:
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)
}
遗憾的是,这导致重叠视图(在下面的屏幕截图中为红色)偏离了几个点。
它似乎总是偏离相同的量。这意味着我可能可以进行硬编码,但这从来都不是一个好主意。在模拟器中使用各种设备以及运行 iOS 8.1.3 的 iPhone 6 对此进行了测试。
我还尝试了其他变体(通过创建我自己的 NSTextContainer 等),灵感来自关于如何获取子字符串的 CGRect 的问题 and “boundingRectForGlyphRange 并不总是适用于所有字符串”
任何想法(除了求助于CoreText)?
尝试通过文本视图的 textContainerInset 调整字形矩形:
var glyphRect = txtView.layoutManager.boundingRectForGlyphRange(glyphRange,
inTextContainer: glyphContainer!)
glyphRect.origin.y += txtView.textContainerInset.top
这应该够了吧!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)