相关疑难解决方法(0)

NSLayoutManager boundingRectForGlyphRange由某些点关闭

我想在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 …
Run Code Online (Sandbox Code Playgroud)

objective-c core-text ios textkit swift

6
推荐指数
1
解决办法
1318
查看次数

标签 统计

core-text ×1

ios ×1

objective-c ×1

swift ×1

textkit ×1