Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Detect if text selected

How can I log every time the user highlights some text in a textview using "selectedRange"?

1 Answer

Stone Preston
Stone Preston
42,016 Points

looks like you can use the textViewDidChangeSelection delegate method of the UITextViewDelegate protocol

maybe try something like

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

   UITextRange *selectedRange = [textView selectedTextRange];
   NSString *selectedText = [textView textInRange:selectedRange];
   NSLog(@"%@", selectedText);
}

It does not seem to do anything. Is there anything else I should add?

Stone Preston
Stone Preston
42,016 Points

you need to set your view controller as the text views delegate in viewDidLoad and make sure your view controller conforms to the UITextView delegate protocol by placing <UITextViewDelegate> after header class declaration

Perfect! I hadn't set the view controller as the text views delegate. Thanks for your help

Stone Preston
Stone Preston
42,016 Points

cool glad you got it figured out