Swift 4.1
In your UITextView
Extension put the below code in a function, and use that in your controller:
You can call this method with your textView instance in the SelectionDidChange delegate method from your view-Controller. Better to wrap this function call with condition textView.selectedRange.length > 0
, to get some text...
let begin = self.beginningOfDocument
let start = self.position(from: begin, offset: selectedRange.location)
let end = self.position(from: position(from: start!, offset: 0)!, offset: selectedRange.length)
let txtRange = self.textRange(from: start!, to: end!)
let txt = self.text(in: txtRange!)
print("Sel Text is \(String(describing: txt))")
We can not use the optional binding to store the selected range, instead you can declare an optional for nsrange type, then use the if- let ... thing.
TextInputComponent
has a property to get the selected text range.
let range = textView.selectedRange
Then you can use range.location
, range.length
values to change attributes of text in the container, etc...