简体   繁体   中英

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

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.

尝试这个

textView.replaceRange(textView.selectedTextRange!, withText: "your text")

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

update:

Swift 5.2

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM