问题
UITextField and UITextView both adopt the UITextInput protocol. UITextView's selectedRange property returns NSRange, where UITextField doesn't have any selection properties/methods. I'd like to use one routine to manage insertion in either UITextField or UITextView.
So I do the following:
id<UITextInput> textInput = nil;
if ([self.aTextView isFirstResponder]) {
textInput = self.aTextView;
} else if ([self.aTextField isFirstResponder]) {
textInput = self.aTextField;
}
if (textInput != nil) {
UITextRange * selectedRange = textInput.selectedTextRange;
// ...
}
Only to promptly crash with 'unrecognized selector sent to instance' on the selectedTextRange property.
What am I doing wrong?
[EDIT: seems to work in iOS 5, but crashes on device in iOS 4. Is this a change in iOS 5? The docs say the protocol is 3.2+.]
回答1:
I verified in my own app that UITextView and UITextField both crash with -[UITextView selectedTextRange]: unrecognized selector
in the iOS 4 simulator but not the iOS 5 simulator.
The answer to this question suggests that the conformance to UITextInput is a new thing in iOS 5: Can I select a specific block of text in a UITextField? . So it appears that the protocol itself is iOS 3.2, but UITextView/Field didn't make use of that protocol before iOS 5.
回答2:
@Absinthe's edit is correct. UITextField
didn't start following the UITextInput
protocol until iOS 5.
来源:https://stackoverflow.com/questions/7923659/uitextinput-protocol-usage-for-uitextfield-and-uitextview-to-manage-selection-re