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

白昼怎懂夜的黑 提交于 2019-12-22 09:55:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!