如何在 swift 中将字符索引从布局管理器转换为字符串比例? 这是我正在使用的代码:
let touchPoint: CGPoint = gesture.locationOfTouch(0, inView: self.definitionLabel)
let index = layoutManager.characterIndexForPoint(touchPoint, inTextContainer: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
请不要告诉我在字符串字符集的第一个索引上使用 advanceBy()
函数,因为像 ò 这样的字符在布局管理器的比例中计数为 2,但 swift 字符串只计算 theme 一次。
最佳答案
从NSLayoutManager
返回的索引是“基于NSString
”,
即从字符串开头算起的 UTF-16 代码单元数
到给定点的角色。 (所以 ò
实际上算作
一个,但表情符号 😀
算二,而标记 🇧🇪
甚至算四。)
要将该索引转换为有效的 Swift String
索引,您可以使用
与 https://stackoverflow.com/a/30404532/1187415 中的方法相同:
let text = ... // the stored text
let i16 = text.utf16.startIndex.advancedBy(index, limit: text.utf16.endIndex)
// i16 is a String.UTF16View.Index
if let strIndex = String.Index(i16, within: text) {
// strIndex is a String.CharacterView.Index
let char = text[strIndex]
print(char)
}
关于ios - 如何在 swift 中将字符索引从布局管理器转换为字符串比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781165/