[英]is it possible to get the index (String.Index) value from the cursor position of a UITextView element in Swift?
我希望從 UITextView 元素的用戶光標位置提取索引值 ( String.Index
)。 我正在使用selectedTextRange
方法來獲取 UITextRange 值。 如何使用它來檢索索引值?
您可以獲得從文檔開頭到所選范圍開頭的選定范圍偏移量,並使用該偏移量來獲取字符串索引,如下所示:
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 ?? "")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.