本文介绍了是否可以从Swift中的UITextView元素的光标位置获取索引(String.Index)值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找从UITextView元素的用户光标位置提取索引值( String.Index
).我正在使用 selectedTextRange
方法获取UITextRange值.如何使用它来检索索引值?
I'm looking to pull the index value (String.Index
) from the user cursor position of a UITextView element. I'm using the selectedTextRange
method to get the UITextRange value. How can I use that to retrieve the index value?
推荐答案
您可以获取从文档开头到所选范围开头的所选范围偏移量,并使用该偏移量获取字符串索引,如下所示:
You can get the selected range offset from the beginning of your document to the start of the selected range and use that offset to get your string index as follow:
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 location = cursorOffset else { return nil }
return Range(.init(location: location, length: 0), in: text)?.lowerBound
}
var cursorDistance: Int? {
guard let cursorIndex = cursorIndex else { return nil }
return text.distance(from: text.startIndex, to: cursorIndex)
}
}
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
func textViewDidChangeSelection(_ textView: UITextView) {
print("Cursor UTF16 Offset:",textView.cursorOffset ?? "")
print("Cursor Index:", textView.cursorIndex ?? "")
print("Cursor distance:", textView.cursorDistance ?? "")
}
}
这篇关于是否可以从Swift中的UITextView元素的光标位置获取索引(String.Index)值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!