UITextField 过早退出 firstResponder

UITextField resigning firstResponder too early

我有两个 UITextField 实例。第一个文本字段的 returnKeyTypeUIReturnKeyNext,第二个文本字段的 returnKeyTypeUIReturnKeyDone。基于 this SO answer,我尝试在单击 'Next' 按钮时退出第一个文本字段的第一响应者,然后让第二个文本字段成为第一响应者。当在第二个文本字段上单击 'Done' 按钮时,第一响应者辞职,键盘消失。

下面是我的代码:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _textFieldOne){
        [_textFieldOne resignFirstResponder];
        [settingsDictionary setObject: _textFieldOne.text forKey:@"TextFieldOneInfo"];
        [settingsDictionary stringValueForKey:@"TextFieldOneInfo"];
        [self postNotificationSettingsUpdate:settingsDictionary];

        didTestPostNotificationSettings = YES;
        [_textFieldTwo becomeFirstResponder];
    }
    if (textField == _textFieldTwo){
        [_textFieldTwo resignFirstResponder];
    }
    return YES;
}

当点击'Next'按钮时,第一个文本字段成功退出第一响应者,第二个文本字段成为新的第一响应者。但是,在单击 'Done' 按钮之前,第二个文本字段 立即 似乎放弃了它的第一响应者状态。

谁能告诉我为什么第二个文本字段在 'Done' 按钮被点击之前就放弃了它的第一响应者状态?谢谢!

EDIT 我已将问题缩小到以下代码行:

[self postNotificationSettingsUpdate:settingsDictionary];

当它被注释掉时,文本字段 return- 按钮操作会按预期运行。

如果您想要切换文本字段,则无需调用 resignFirstResponder。我已经成功地尝试过这个:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _textFieldOne){
        [_textFieldTwo becomeFirstResponder];
    }
    else if (textField == _textFieldTwo){
        [textField resignFirstResponder];
    }

return YES;

}

经过一番挖掘,我相信我找到了解决方案。

具体违规代码行如下:

    [self postNotificationSettingsUpdate:settingsDictionary];

调用下面的方法:

- (void)postNotificationSettingsUpdate:(NSDictionary *) updateDict {
    [self.dataCache setUserNotificationSettings:updateDict];
}

...通过网络连接发送字典信息。

这些文本视图存储在 UITableView 行中。在我看来发生的事情是,当调用此方法时,它重新加载了视图。解决方案是在开始和结束时添加对 [tableView beginUpdates];[tableView endUpdates]; 的调用 - (BOOL)textFieldShouldReturn:(UITextField *)textField

这样做之后,当第一个文本字段的 'Next' 按钮被选中时,第二个文本字段将成为第一响应者,而当 'Done'按钮被选中。