3

我需要在我的 UILabel 中找到我的角色位置(它有 ParagraphLineSpacing 和多行的 AttributedText),

我有我的角色索引,但现在我无法从我的索引中获取 X 和 Y 坐标。

我找到了这个http://techqa.info/programming/question/19417776/how-do-i-locate-the-cgrect-for-a-substring-of-text-in-a-uilabel

我翻译成我的 Swift 3.1 代码

func boundingRect(forCharacterRange range: NSRange) -> CGRect {

    let textStorage = NSTextStorage(attributedString: self.attributedText!)
    let layoutManager = NSLayoutManager()
    textStorage.addLayoutManager(layoutManager)
    let textContainer = NSTextContainer(size: bounds.size)
    textContainer.lineFragmentPadding = 0
    layoutManager.addTextContainer(textContainer)
    var glyphRange: NSRange
    // Convert the range for glyphs.

    layoutManager.characterRange(forGlyphRange: range, actualGlyphRange: glyphRange)
    return layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)

}

但是,不幸的是,我不能真正使用这段代码,因为实际 GlyphRange 询问 NSRangePointer,而不是 NSRange,所以我将翻译后的代码更改为

func boundingRect(forCharacterRange range: NSRange) -> CGRect {

    let textStorage = NSTextStorage(attributedString: self.attributedText!)
    let layoutManager = NSLayoutManager()
    textStorage.addLayoutManager(layoutManager)
    let textContainer = NSTextContainer(size: bounds.size)
    textContainer.lineFragmentPadding = 0
    layoutManager.addTextContainer(textContainer)
    //var glyphRange: NSRange

    let a = MemoryLayout<NSRange>.size
    let pointer:NSRangePointer = NSRangePointer.allocate(capacity: a)
    layoutManager.characterRange(forGlyphRange: range, actualGlyphRange: pointer)
    return layoutManager.boundingRect(forGlyphRange: range, in: textContainer)
}

我不明白什么

 var glyphRange: NSrange 

用法,所以我删除了它,现在代码可以工作了,但结果有 60% 不准确,尤其是当我的角色位于第二行或第三行时。我把这里的翻译搞砸了吗?或者有没有更好的方法来准确地获取我的角色坐标?

我用

NSMakeRange(index, 1) 

让我的参数找到一个特定的字符

=======更新=======

我曾尝试自定义 UITextView 来访问其布局管理器,但不幸的是,如果有 2 行或更多行,位置仍然不准确。(仅当我的 textView 中只有 1 行时才准确)

class LyricTextView: UITextView {
  func boundingRect(forCharacterRange range: NSRange) -> CGRect {
    let inset = self.textContainerInset
    let rect = self.layoutManager.boundingRect(forGlyphRange: range, in: textContainer).offsetBy(dx: inset.left, dy: inset.top)

    return rect
  }
}

我在这个新代码中遗漏了什么吗?快完成了

4

1 回答 1

0

一个更容易解决编译错误的方法是使用这个:

var glyphRange = NSRange()
layoutManager.characterRange(forGlyphRange: range, actualGlyphRange: &glyphRange)

但是,当我尝试它时,我也只能在第一行获得正确的文本矩形。

如果你可以使用 a UITextView,你可以访问它的布局管理器和文本容器:

@IBOutlet var textView: UITextView!
...

let rect = textView!.layoutManager.boundingRect(
    forGlyphRange: glyphRange, in: textView!.textContainer)

看来您还需要考虑文本视图的文本容器插图,因此以下内容对我有用,可以在第二行获得文本的边界矩形:

let inset = textView!.textContainerInset
let rect = textView!.layoutManager.boundingRect(
    forGlyphRange: glyphRange, in: textView!.textContainer)
    .offsetBy(dx: inset.left, dy: inset.top)

如果有人找到适用于UILabel.

于 2017-05-27T12:22:13.637 回答