Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a selected range of text from a UITextView or UITextField

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

}
like image 523
Mr Ordinary Avatar asked Mar 26 '13 05:03

Mr Ordinary


2 Answers

You can try this,

- (void)textViewDidChangeSelection:(UITextView *)textView {

   UITextRange *selectedRange = [textView selectedTextRange];
   NSString *selectedText = [textView textInRange:selectedRange];
}
like image 176
Iducool Avatar answered Sep 28 '22 16:09

Iducool


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:

  • Selecting text from a UITextField is done in the same way.
  • The range is a 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.
like image 29
Suragch Avatar answered Sep 28 '22 17:09

Suragch