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

2.2k Views Asked by At

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

There are 3 best solutions below

1
Eppilo On BEST ANSWER

Try this... Inside your button's IBAction use this (please do not use forced optional unwrapping) or else if the textView has no selection or cursor, the app might crash:

let txt = "whatever you want"
if let range = handleToYourTextView.selectedTextRange {
   // From your question I assume that you do not want to replace a selection, only insert some text where the cursor is.
   if range.start == range.end {
      handleToYourTextView.replaceRange(range, withText: txt)
   }
}
0
techloverr On

try this

textView.replaceRange(textView.selectedTextRange!, withText: "your text")
0
Steve Robertson On

update:

Swift 5.2

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