繁体   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