I am trying to get the selected range of text from a UITextView (and or UITextField) so that I can edit the selected text, or modify an attributed string. The method below is triggered when I make a selection, but the code in the method returns null values.
- (void)textViewDidChangeSelection:(UITextView *)textView {
UITextRange *selectedRange = [textField selectedTextRange];
NSLog(@"Start: %@ <> End: %@", selectedRange.start, selectedRange.end);
}
You can try this,
- (void)textViewDidChangeSelection:(UITextView *)textView {
UITextRange *selectedRange = [textView selectedTextRange];
NSString *selectedText = [textView textInRange:selectedRange];
}
Swift
First get the selected text range, and then use that range to get the actual text:
if let textRange = myTextView.selectedTextRange {
let selectedText = myTextView.text(in: textRange)
// ...
}
Notes:
UITextField
is done in the same way.UITextRange
, not an NSRange
. This allows for proper selection of things like emoji and extended grapheme clusters. See this answer for related details about this.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With