我需要在我的 UILabel 中找到我的角色位置(它有 ParagraphLineSpacing 和多行的 AttributedText),
我有我的角色索引,但现在我无法从我的索引中获取 X 和 Y 坐标。
我翻译成我的 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
}
}
我在这个新代码中遗漏了什么吗?快完成了