Get a range of selected text in UITextField as an NSRange is iOS 4

2.1k views Asked by At

I've been doing it using selectedTextRange and beginningOfDocument properties from the UITextInput protocol, but as I just learned in the post below, UITextField only starts adhering to the UITextInput protocol in iOS 5, so my app is crashing in iOS 4.3. I need another way to do this in iOS 4.3.

UITextInput protocol usage for UITextField and UITextView to manage selection results in crash.

Here's what I'm doing now (self is my UITextField subclass):

UITextRange *selectedTextRange = self.selectedTextRange;
NSUInteger location = [self offsetFromPosition:self.beginningOfDocument
                                        toPosition:selectedTextRange.start];
NSUInteger length = [self offsetFromPosition:selectedTextRange.start
                                      toPosition:selectedTextRange.end];
NSRange selectedRange = NSMakeRange(location, length);
1

There are 1 answers

1
David H On BEST ANSWER

Suppose a user has selected some text in the UITextField. If its iOS 4 add a tag line below the field that says "Select and Copy", then you can grab the text off the clipboard (not sure if you can get notified when clipboard changes though).

Or, you could even have them tap on some key - even the delete key, and in the text delegate method "shouldChangeCharactersInRange:", you can get the range, then return NO so as to not change it.