Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting selection change on a UITextView?

Is there a way to detect when the user changes the range of the selected text in a textview (In a subclass of UITextView)? I couldn't find any NSNotification. I tried observing keyvalues but the observer for selected range does not get called

[self addObserver:self forKeyPath:@"selectedRange" options:NSKeyValueObservingOptionNew context:nil];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqual:@"selectedRange"])
    {
        // Do stuff
    }
}

I DO NOT want to use the delegate method of UITextView

like image 644
aryaxt Avatar asked Jul 27 '13 17:07

aryaxt


People also ask

What is UITextView?

UITextView supports the display of text using custom style information and also supports text editing. You typically use a text view to display multiple lines of text, such as when displaying the body of a large text document. This class supports multiple text styles through use of the attributedText property.

Is UITextView scrollable?

UITextView should only be able to scroll Horizontally or Vertically. (Need to disable the diagonal scroll).


2 Answers

UITextView adopts the UITextInput protocol. That protocol includes a required selectedTextRange read/write property. That is the property you want to respond to changes of.

While you could observe that property, the simplest approach is to override the -setSelectedTextRange: method in your subclass and perform whatever additional behaviours you need in there. (You may or may not want to confirm that the range is actually changing, depending on your particular design.)

like image 158
Bored Astronaut Avatar answered Sep 29 '22 17:09

Bored Astronaut


UITextView's delegate () conforms to this since iOS2

-(void)textViewDidChangeSelection:(UITextView *)textView {
    //read textView.selectedRange
}

I also personally like to manually trigger it when dismissing a keyboard since that also is a selection change in my opinion but won't trigger the delegate callback on its own (an overlooking on Apple's part in my humble opinion)

-(void)textViewDidEndEditing:(UITextView *)textView {
    textView.selectedRange = NSMakeRange(0, 0);
    [self textViewDidChangeSelection:textView];
}
like image 26
Albert Renshaw Avatar answered Sep 29 '22 17:09

Albert Renshaw