How to programmatically enter text in UITextView at the current cursor position

Viewed 1944

I would like to add (some predefined) text at the current cursor position in a UITextView using Swift. So if I have a UITextField named txtField that has some text in it already such as "this is a beautiful valley" and I tap in the area between "a" and "beautiful" so that the cursor is now in the space between "a" and "beautiful" and then click a Button on my user interface a string of text such as "very" will get typed at the cursor position, so that the text in the UITextView will now become "this is a very beautiful valley". At the end of this operation (after button click event) I would the cursor to be just after the word "very". Many thanks for your help. I can see some question on the forum with similar themes, but the answers are in Objective C. I suicidal like help using Swift.

3 Answers

update:

Swift 5.2

    let txt = "whatever you want"
    if let range = myTextView.selectedTextRange {
       if range.start == range.end {
        myTextView.replace(range, withText: txt)
       }
Related