NSLayoutManager boundingRectForGlyphRange关闭了一些点 [英] NSLayoutManager boundingRectForGlyphRange off by some Points

查看:172
本文介绍了NSLayoutManager boundingRectForGlyphRange关闭了一些点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想突出显示" UITextView中的特定单词,而不是用纯色(可通过NSAttributedString来实现),而是使用渐变色和其他一些奇特的效果.

I want to "highlight" specific words in UITextView, not with a solid color (which would be possible via NSAttributedString), but rather with a gradient and maybe some other fancy effects.

因此,我认为有必要手动创建视图并使用给定文本的边界矩形对其进行覆盖(或覆盖).

Hence, I decided it would be necessary to manually create a view and overlay (or underlay) it using the bounding rectangles of the given text.

令我惊讶的是,事实证明这很简单.示例位于UIViewController内部,txtView是作为IBOutlet连接的UITextView:

To my surprise this turned out to be pretty straightforward. Example is inside a UIViewController, txtView being a UITextView connected as 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)
}

可悲的是,这导致了重叠视图(在下面的屏幕截图中以红色显示),偏离了几分.

Sadly, this leads to the overlain view (in red in the below screenshot), being off by a few points.

它似乎总是偏离相同的量.这意味着我可能可以进行硬编码,但这从来都不是一个好主意.在具有各种设备的Simulator中以及在装有iOS 8.1.3.的iPhone 6上进行了测试.

It always seems to be off by the same amount. Which would mean I could probably hardcode, but that has never been a good idea. Tested this in Simulator with various devices and on an iPhone 6 with iOS 8.1.3.

我还尝试了其他变体(通过创建自己的NSTextContainer等),受到"boundingRectForGlyphRange并不总是适用于所有字符串"

I also tried other variations (by creating my own NSTextContainer etc.) as inspired by the question on how to get a CGRect for a substring and "boundingRectForGlyphRange does not always work for all strings"

任何想法(除了​​重新排序到CoreText )?

推荐答案

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

Try adjusting the glyph rect by the textview's textContainerInset:

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

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

那应该可以解决问题!

这篇关于NSLayoutManager boundingRectForGlyphRange关闭了一些点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆