草庐IT

ios - NSLayoutManager boundingRectForGlyphRange 关闭一些点

coder 2023-09-04 原文

我想在 UITextView 中“突出显示”特定的单词,而不是使用纯色(可以通过 NSAttributedString),而是使用渐变和其他一些奇特的效果。

因此,我决定有必要手动创建一个 View 并使用给定文本的边界矩形覆盖(或底层)它。

令我惊讶的是,事实证明这非常简单。示例在 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)
}

遗憾的是,这导致覆盖 View (在下面的屏幕截图中以红色显示)偏离了几个点。

它似乎总是有相同的偏差。这意味着我可能会硬编码,但这从来都不是一个好主意。在带有各种设备的模拟器中以及在装有 iOS 8.1.3 的 iPhone 6 上对此进行了测试。

我还尝试了受 the question on how to get a CGRect for a substring 启发的其他变体(通过创建我自己的 NSTextContainer 等)和 "boundingRectForGlyphRange does not always work for all strings"

有什么想法(除了 resorting to CoreText )吗?

最佳答案

尝试通过 textview 的 textContainerInset 调整字形矩形:

var glyphRect = txtView.layoutManager.boundingRectForGlyphRange(glyphRange,
        inTextContainer: glyphContainer!)

glyphRect.origin.y += txtView.textContainerInset.top

这应该可以解决问题!

关于ios - NSLayoutManager boundingRectForGlyphRange 关闭一些点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330772/

有关ios - NSLayoutManager boundingRectForGlyphRange 关闭一些点的更多相关文章

随机推荐