ios 将焦点设置为 tableCell 中的 UITextField

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8883730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:21:52  来源:igfitidea点击:

Set focus to UITextField in tableCell

ioseventsuitableviewuitextfield

提问by nabiullinas

I am creating a table view with UITextFields dynamically.

我正在用UITextFields 动态创建一个表视图。

l_textField = [[UITextField alloc] initWithFrame:TextFieldFrame];
l_textField.tag = cellRow;

l_textField.delegate = self;
l_textField.font = [UIFont boldSystemFontOfSize:14];
l_textField.textColor = [UIColor blackColor];
[l_textField setEnabled:YES];

[cell.contentView addSubview:l_textField];

And now I want to set focus on this text field when user touch cell. I write this

现在我想在用户触摸单元格时将焦点设置在此文本字段上。我写这个

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath {
    UITextField* field = (UITextField *) [tblView viewWithTag: newIndexPath.row];
    [field resignFirstResponder];
}

But this doesn't work

但这不起作用

回答by Saurabh

change [field resignFirstResponder];with [field becomeFirstResponder];

改变[field resignFirstResponder];[field becomeFirstResponder];

resignFirstResponderis used to remove keyboard (focus) from text field

resignFirstResponder用于从文本字段中删除键盘(焦点)

回答by mxmlc

I've faced the same issue here, even using correctly the [field becomeFirstResponder];.

我在这里遇到了同样的问题,即使正确使用[field becomeFirstResponder];.

I also used tags to get the objects I have inside the cell. Your didSelectRowAtIndexPathshould look like this to get the right cell:

我还使用标签来获取单元格内的对象。您didSelectRowAtIndexPath应该看起来像这样以获得正确的单元格:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    currentRow = indexPath.row;

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UITextField *indexField = (UITextField *)[cell viewWithTag:101];
    [indexField becomeFirstResponder];
}

It worked like a charm for me.

它对我来说就像一种魅力。

回答by yousaf nisar

Swift 3

斯威夫特 3

myTextField.becomeFirstResponder()

My Code. Take index path of current cell. And get cell of next indexpath.row. And called ** cell1.txtFindings.becomeFirstResponder() **

我的代码。取当前单元格的索引路径。并获取下一个 indexpath.row 的单元格。并调用 ** cell1.txtFindings.becomeFirstResponder() **

  if  let textFieldIndexPath = specsListView.indexPath(for: cell){
        let newIndexPath = IndexPath(row: textFieldIndexPath.row + 1, section: 0)

        if let cell1: SpecsTableViewCell = specsListView.cellForRow(at: newIndexPath) as? SpecsTableViewCell{
            cell1.txtFindings.becomeFirstResponder()
        }
}