If I have a series of table cells, each with a text field, how would I make a specific text 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With