首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSLayoutManager boundingRectForGlyphRange差了几个点

NSLayoutManager boundingRectForGlyphRange差了几个点
EN

Stack Overflow用户
提问于 2015-02-04 20:25:27
回答 1查看 1.7K关注 0票数 6

我想在UITextView中“突出”特定的单词,不是用纯色(通过NSAttributedString就可以了),而是用渐变或者其他一些花哨的效果。

因此,我决定需要手动创建视图,并使用给定文本的边界矩形覆盖(或衬垫)它。

令我惊讶的是,事实证明这是非常简单的。示例位于UIViewController中,txtView是以IBOutlet形式连接的UITextView

代码语言:javascript
复制
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)吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-04 22:25:47

尝试通过文本视图的textContainerInset调整字形重排:

代码语言:javascript
复制
var glyphRect = txtView.layoutManager.boundingRectForGlyphRange(glyphRange,
        inTextContainer: glyphContainer!)

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

那应该就行了!

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28330772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档