UITextInput protocol usage for UITextField and UIT

2019-05-10 17:03发布

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+.]

2条回答
我只想做你的唯一
2楼-- · 2019-05-10 17:32

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.

查看更多
我命由我不由天
3楼-- · 2019-05-10 17:33

@Absinthe's edit is correct. UITextField didn't start following the UITextInput protocol until iOS 5.

查看更多
登录 后发表回答