【发布时间】:2011-10-05 12:24:02
【问题描述】:
如果我有一系列表格单元格,每个单元格都有一个文本字段,我如何让特定的文本字段成为第一响应者?
【问题讨论】:
标签: iphone objective-c ios uitextfield
如果我有一系列表格单元格,每个单元格都有一个文本字段,我如何让特定的文本字段成为第一响应者?
【问题讨论】:
标签: iphone objective-c ios uitextfield
// 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;
}
【讨论】:
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
【讨论】:
如果您希望文本字段在加载表格视图后成为第一响应者,
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];
【讨论】:
// 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 单元格中生成 selected(becomeFirstResponder) 文本字段。
【讨论】:
UITextField 继承自 UIResponder,它实现了 becomeFirstResponder 消息。
【讨论】: