3

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.

Faheem Ahmad
  • 99
  • 10

3 Answers3

2

try this

textView.replaceRange(textView.selectedTextRange!, withText: "your text")
techloverr
  • 2,597
  • 1
  • 16
  • 28
2

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)
   }
}
Eppilo
  • 763
  • 6
  • 19
0

update:

Swift 5.2

    let txt = "whatever you want"
    if let range = myTextView.selectedTextRange {
       if range.start == range.end {
        myTextView.replace(range, withText: txt)
       }
Steve Robertson
  • 209
  • 5
  • 12