DaveJ
DaveJ

Reputation: 65

is it possible to get the index (String.Index) value from the cursor position of a UITextView element in Swift?

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?

Upvotes: 3

Views: 1876

Answers (2)

Míng
Míng

Reputation: 2608

let range = Range(textView.selectedRange, in: textView.text)

The "cursor position" is range.lowerBound.

Upvotes: 0

Leo Dabus
Leo Dabus

Reputation: 236360

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 ?? "")
    }
}

Upvotes: 5

Related Questions