如何在表格单元格中创建UITextField成为第一响应者?

问题描述 投票:4回答:5

如果我有一系列表格单元格,每个表格单元格都有一个文本字段,我将如何使特定的文本字段成为第一个响应者?

iphone objective-c ios uitextfield
5个回答
5
投票
// Customize the appearance of table view cells.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) 
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    UITextField *textField = [[UitextField alloc] init];
 ...
     textField.delegate = self;
     textField.tag = indexPath.row;
     [cell addSubView:textField];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

我希望这可以帮助你......


1
投票
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) 
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

}
if(indexPath.row==1)
    {
        [cell.txtField becomeFirstResponder];
    }
return cell;
}

上面的代码在第二个UItableView单元格中选择(becomeFirstResponder)文本字段。谢谢


1
投票

Swift 4:要使textfield成为tableview中的第一个响应者,只需将此扩展添加到tableView:

extension UITableView {
    func becomeFirstResponderTextField() {
        outer: for cell in visibleCells {
            for view in cell.contentView.subviews {
                if let textfield = view as? UITextField {
                    textfield.becomeFirstResponder()
                    break outer
                }
            }
        }
    }
}

然后在viewDidAppear()中调用becomeFirstResponderTextField():

func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    tableView.becomeFirstResponderTextField()
}

注意:我被认为是可以搜索的visibleCells


0
投票

如果希望文本字段在加载表视图后成为第一响应者,

NSIndexPath *indexPath = /* Index path of the cell containg the text field */;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// Assuming that you have set the text field's "tag" to 100
UITextField *textField = (UITextField *)[cell viewWithTag:100];
// Make it the first responder
[textField becomeFirstResponder];

0
投票

UITextField继承自UIResponder,后者实现了becomeFirstResponder消息。

© www.soinside.com 2019 - 2024. All rights reserved.