【问题标题】:Remove keyboard when table cell selected选择表格单元格时删除键盘
【发布时间】:2012-01-14 23:22:19
【问题描述】:

我有一个这样的模式设置:

尽管看起来,前两个字段是 UITextFields,它们成为第一响应者并显示键盘。第三个 'Department' 项是一个表视图并推送另一个视图。

我已经实现了一个滚动视图,以便在编辑任一字段时,用户可以滚动并到达部门单元格:

当它被选中时,在推送之前,我想隐藏键盘。这是一个小细节,但请尝试在 Apple 的“日历”应用程序中添加一个新事件。它以第一个文本字段作为第一响应者打开(因此存在键盘)。如果您选择开始/结束单元格,则键盘会在下一个视图被按下时隐藏。

我如何实现这一目标?作为我尝试的测试:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"hiding keyboard");
if ([ingredientName isFirstResponder]) {
    NSLog(@"resigning name field");
    [ingredientName resignFirstResponder];
}
else if ([ingredientAmount isFirstResponder]){
    NSLog(@"resigning amount field");
    [ingredientAmount resignFirstResponder];
}

}

日志记录确认这些正在被调用。但键盘并没有隐藏。当视图滑出时,它只是保持在原位。返回时,前一个字段仍然有焦点(键盘不在)。

有什么想法吗?

【问题讨论】:

    标签: ios uiviewcontroller uiscrollview uitextfield resignfirstresponder


    【解决方案1】:

    resignFrstResponder 在您使用模式视图时不会关闭键盘。

    另一位开发人员在这里找到了解决此问题的方法:http://viraj-workstuff.blogspot.com/2010/12/resignfirstresponder-does-not-hide.html

    【讨论】:

    • 这可能已经过时了。通过将其连接到相同的代码,我可以成功地让第一响应者在模式中的其他操作(例如点击“返回”键)上辞职。
    • resignFirstResponder 确实在模态视图中工作。这里的问题是 didSelectRowAtIndexPath 在 prepareForSegue 之后被调用。
    • 它不适合我,所以我非常感谢链接
    【解决方案2】:

    不是很优雅,但尝试使用临时的、不可见的UITextField 窃取第一响应者状态:

    -(void)dismissKeyboard {
        UITextField *textField;
        textField=[[UITextField alloc] initWithFrame:CGRectZero];
        [self.view addSubview:textField];
        [textField becomeFirstResponder];
        [textField resignFirstResponder];
        [textField removeFromSuperview];
        // [textField release] // uncomment if not using ARC
    }
    

    【讨论】:

      【解决方案3】:

      两件事: 您是否使用 segue 来推动其他 VC?如果是这样,请在 prepareForSegue 方法中退出键盘。

      如果没有,请尝试使用 willSelectRowForIndexPath 而不是 didSelectRowAtIndexPath

      【讨论】:

      • 我正在使用 segue,并且在 prepareForSegue 中插入代码就可以了。有时很容易错过显而易见的事情 - 谢谢!
      • 没问题,我每天都想念显而易见的事情:)
      猜你喜欢
      • 1970-01-01
      • 2015-10-30
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 2013-05-02
      相关资源
      最近更新 更多