如何以编程方式在当前光标位置的 UITextView 中输入文本

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

我想使用 Swift 在 UITextView 的当前光标位置添加(一些预定义的)文本。因此,如果我有一个名为 txtField 的 UITextField,其中已经包含一些文本,例如 "this is a beautiful valley",然后我点击 "a" 和 "beautiful" 之间的区域,以便光标现在位于 space 在 "a" 和 "beautiful" 之间,然后在我的用户界面上单击一个按钮,将在光标位置键入诸如 "very" 之类的文本字符串,以便 UITextView 中的文本现在将变为 "this is a very beautiful valley"。在此操作结束时(在按钮单击事件之后),我希望光标刚好位于单词 "very" 之后。非常感谢您的帮助。我可以在论坛上看到一些类似主题的问题,但答案在 Objective C 中。我想用 Swift 帮助自杀。

试试这个

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

试试这个...在按钮的 IBAction 中使用这个(请不要使用强制可选展开)否则如果 textView 没有选择或光标,应用程序可能会崩溃:

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

更新:

Swift 5.2

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