-2

UITextView When input , like this how to get the selected text range,i need to remove the selected text.enter image description here

Y.Silient
  • 1
  • 2

2 Answers2

5

Since UITextView conforms to the UITextInput protocol, you can ask it for its selectedTextRange, and then ask it to replace that range with an empty string:

if let range = textView.selectedTextRange {
    textView.replace(range, withText: "")
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • It's a text view, not a text field. It has a `selectedRange` property of its own. – matt Dec 04 '16 at 04:13
  • [Yes, I know.](http://stackoverflow.com/a/12990127/77567) If you think `selectedRange` is better for some reason, please post an answer showing how to use it to answer Y.Silient's question. I like my answer for two reasons. One, it works for `UITextField` too, so it's nice recipe to have in your cookbook. Two, I didn't have to test it to know it's correct. When the text view has no selection (not even an insertion point), `selectedTextRange` is nil. I don't know what `selectedRange` is under that circumstance so I'd have to run a test. – rob mayoff Dec 04 '16 at 05:17
  • yes,selectedRange.length is nil.So there is no way I can get it – Y.Silient Dec 05 '16 at 03:09
0

[textView markedTextRange] & textView.textInputMode.primaryLanguage Would be useful

Y.Silient
  • 1
  • 2