在自定义UITableViewCell中使用UITextField的resignFirstResponder问题

时间:2014-02-05 07:27:25

标签: ios iphone objective-c uitableview

我有UITableView个自定义UITableViewCell每个单元格包含UILabelUITextField,如下所示。我在键盘顶部添加了一个Done按钮,用于隐藏键盘。

enter image description here

现在假设第二行的textField是firstResponder,那时我将表格视图滚动到顶部并从可见的rect移出第二行。现在,如果我按Done键然后在我使用[[self view] endEditing:YES];的地方被解雇,应用程序就崩溃了。

要解决这个问题,我实施了以下方法,并取得了成功。

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    for(UIView *contentView in [[cell contentView] subviews])
    {
        if([contentView isKindOfClass:[UIView class]])
        {
            for(UITextField *textField in [contentView subviews])
            {
                if([textField isKindOfClass:[UITextField class]] && [textField isFirstResponder])
                {
                    [textField resignFirstResponder];
                    break;
                }
            }
        }
    }
}

现在的问题是,当第二行从可见的矩形移出时,上面的方法被触发并且键盘会按预期自动隐藏。但当时我将表格视图向下拖动并再次在第二行移动到可见的矩形时它的颜色发生了变化。  enter image description here

要解决颜色问题,我实现了以下方法,但它无法正常工作

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setBackgroundColor:[UIColor clearColor]];
}

不仅仅是颜色问题。再次,如果我触摸第二行键盘的textField,如果我执行相同的方案tableView didEndDisplayingCell方法没有为该单元格触发。即使我按下Done密钥应用程序也崩溃了。异常制动点指向[[self view] endEditing:YES];,错误显示为enter image description here

伙计们请帮助我。我浪费了很多时间来弄清楚但是我失败了。

1 个答案:

答案 0 :(得分:2)

当一个单元格被滚动到视图之外并被删除时,UIKit会调用didEndDisplayingCell。但是,当它具有焦点的编辑控件时,不会调用didEndDisplayingCell。

一种可能的替代方法是通过设置

来关闭拖动键盘
tableView.keyboardDismissMode = .OnDrag

这会导致UITextView放弃第一个响应者,从而调用didEndDisplayingCell。

更多细节here

相关问题