Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a UITextField in a table cell become first responder?

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?

like image 971
cannyboy Avatar asked Oct 05 '11 12:10

cannyboy


2 Answers

// 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;
}
like image 194
Nilesh Kikani Avatar answered Nov 01 '22 18:11

Nilesh Kikani


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

like image 4
Yahya Alshaar Avatar answered Nov 01 '22 20:11

Yahya Alshaar