如果我有一系列表格单元格,每个表格单元格都有一个文本字段,我将如何使特定的文本字段成为第一个响应者?
答案 0 :(得分: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 :(得分: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)文本字段。谢谢
答案 2 :(得分: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答案 3 :(得分: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];
答案 4 :(得分:0)
UITextField继承自UIResponder,它实现了becomeFirstResponder消息。