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
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.
UITextView should only be able to scroll Horizontally or Vertically. (Need to disable the diagonal scroll).
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.)
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];
}
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