first responder is not being set correctly

后端 未结 2 1298
清歌不尽
清歌不尽 2021-01-27 07:34

I have a grouped table view and trying to set a new first responder to a text field when the user hits enter.

This is nothing new to me, and my code worked before I made

2条回答
  •  -上瘾入骨i
    2021-01-27 08:15

    By comments, the field is inside a modal (presented) controller.

    First an explanation - by default, if a text field in a modal controller loses focus, the keyboard is not hidden. This is controlled by method -[UIViewController disablesAutomaticKeyboardDismissal]

    The default implementation of this method returns YES when the modal presentation style of the view controller is set to UIModalPresentationFormSheet and returns NO for other presentation styles. Thus, the system normally does not allow the keyboard to be dismissed for modal forms.

    This explains why the keyboard behaves the way it behaves. No text field is focused and the keyboard is not hidden only because we are inside a modal controller.

    So, what happens? We know that the current text field resigns first responder and either no view becomes first responder or a non-editable view becomes first responder.

    Well, you whole code looks very suspicious:

    ObjectEditField *field = [group.fields objectAtIndex:i];
    

    Here we have an object of type ObjectEditField

    [field isKindOfClass:[UITextField class]]
    

    Now, we are testing, if the field is a subclass of UITextField. That's very suspicious. If it's ObjectEditField, how it can be UITextField, too?

    Let's continue

    UITextField *textField = (UITextField *)field;
    

    Okey, let's assume it's a UITextField

    if (![textField.field isFirstResponder]) {
    

    Again, something very suspicious. A UITextField has no field property.

    So:

    [textField.field becomeFirstResponder];
    

    is called on an unknown object. We don't even know if it's a UITextField.

    Note that most of the code should issue warnings in your IDE.

    Solution:

    1. Clean up your code, check warnings.
    2. Put a NSLog(@"%@", textField.field) before the becomeFirstResponder call. Check the log.

提交回复
热议问题