2017-06-13 29 views
1

我期待从UITextView元素的用户光标位置拉取索引值(String.Index)。我正在使用selectedTextRange方法来获取UITextRange值。我怎样才能使用它来检索索引值?是否有可能从Swift中的UITextView元素的游标位置获取index(String.Index)值?

+0

这可以帮助你https://开头stackoverflow.com/questions/34922331/getting-and-setting-cursor-position-of-uitextfield-and-uitextview-in-swift – rmp

+0

@rmp这提供了很多见解!谢谢! – DaveJ

回答

1

就可以得到所选择的范围从文档的开始偏移到所选范围和使用这些偏移,让您的字符串索引如下开始:

extension UITextView { 
    var cursorOffset: Int? { 
     guard let range = selectedTextRange else { return nil } 
     return offset(from: beginningOfDocument, to: range.start) 
    } 
    var cursorIndex: String.Index? { 
     guard let cursorOffset = cursorOffset else { return nil } 
     return text.index(text.startIndex, offsetBy: cursorOffset, limitedBy: text.endIndex) 
    } 
} 
+0

太棒了!谢谢! – DaveJ

+0

欢迎您 –

+0

我相信这会对使用表情符号和其他特殊字符的字符串产生问题,因为这里使用的'UITextView'方法会根据字符串的UTF-16编码给出范围和偏移量,而String索引( _:offsetBy:limitedBy:)'方法使用实际字符。 – rmaddy

相关问题