ios - NSLayoutManager boundingRectForGlyphRange 关闭一些点

标签 ios objective-c swift core-text textkit

我想在 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 (在下面的屏幕截图中以红色显示)偏离了几个点。

Simulator Screenshot showing the red rectangle being off by a few points

它似乎总是有相同的偏差。这意味着我可能会硬编码,但这从来都不是一个好主意。在带有各种设备的模拟器中以及在装有 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 - 添加核心数据项后以编程方式生成 View

php - 保存图像并具有 PHP 后端 : how to increase speed? 的 iOS 应用程序的流程

objective-c - 从 JSON 数组 objective-c 获取值时出现问题

iphone - 如何从 Objective-C 计算我的应用程序安装日期和设备日期之间的日期计数差异

ios - 我的模态视图不旋转

ios - 在不延迟当前操作的情况下触发 NSNotification

ios - UITableView Selected Row Position keep stay

ios - 在运行 iOS 11 的 iPad 上禁用 anchor 预览

ios - 如何让 UILabel 每秒更改 NSArray 中每个项目的文本,然后再次旋转?

ios - UINavigationBar:添加无法更改颜色或标题的导航栏