ios - 如何在 swift 中将字符索引从布局管理器转换为字符串比例

标签 ios swift cocoa cocoa-touch

如何在 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/

相关文章:

arrays - Swift - 创建圆并添加到数组中

macos - 您如何使用 Swift 在 Cocoa 应用程序的 View 之间导航?

objective-c - 从带有附件和主题的外部应用程序打开 Mail.app

ios - 不使用 OCMClassMock 调用方法

ios - 可操作的通知不显示操作 Swift 4

ios - swift 中的 viewControllers indexOfObject

ios - SwiftUI View 入门代码在添加到现有项目时提示 `inheritance from non-protocol type ' View'`

iphone - 阻止 View 消失

ios - TableView 不更新

ios - 如何在 IQKeyboardManager iOS Swift 3 中隐藏工具栏