If I have a series of table cells, each with a text field, how would I make a specific tex开发者_JAVA百科t field become the first responder?
// 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:To make textfield the first responder in tableview simply add this extension to 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
}
}
}
}
}
Then in viewDidAppear() call becomeFirstResponderTextField():
func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.becomeFirstResponderTextField()
}
Note: I am considered visibleCells to search through
If you want the text field to become first responder after loading the table view,
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;
}
Above code make selected(becomeFirstResponder)
textfield in second UItableView cell.
The UITextField inherits from UIResponder, which implements the becomeFirstResponder message.
精彩评论