簡體   English   中英

是否可以從 Swift 中 UITextView 元素的光標位置獲取索引 (String.Index) 值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM