UITextField in UITableViewCell won't accept becomeFirstResponder

I want to be allow the user of my app to tap a button which creates a new UITableViewCell that contains a UITextField. The app must allow the user to enter data from the keyboard for that cell. Once the cell is edited, it cannot be edited later. I have added the UITextField to the UITableViewCell in the storyboard.

The code below is working for the first row only - when the Add button is tapped, the UITextField appears empty and becomes the first responder (the keyboard appears). Clicking my Done button on the keyboard adds the new text to the tableview's array and resigns the first responder. But when the Add button is tapped again, the new row is created but the text field does not become the new first responder. If I tap the new row, the keyboard appears correctly.

- (void)addButtonTapped:(id)sender{
    [self.players insertObject:@"" atIndex:0];
    [self.tableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"players cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    NSString *cellText = self.players[indexPath.row];

    UITextField *nameField = (UITextField *)[cell.contentView.subviews lastObject];
    nameField.delegate = self;
    nameField.inputAccessoryView = [self makeKeyboardToolbar];
    nameField.text = cellText;

    // only set first responder if text to be diplayed is an empty string
    if (cellText.length == 0) {
            NSLog(@"canBecomeFirstResponder %@",nameField.canBecomeFirstResponder?@"Y":@"N");
            BOOL isFirst = [nameField becomeFirstResponder];
            NSLog(@"is first? %@",isFirst?@"Y":@"N");
    }
    return cell;
}

What is really strange is found in the NSLog messages. The 'canBecomeFirstResponder' message ALWAYS is Yes, but the 'isFirst?' is ALWAYS No, even when the keyboard appears for the first row.

I use a UITextField property to save a pointer to the current first responder in the delegate method and then update the data array and resign the first responder in my doneWithKeyboard method, which is called by my Done button:

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.currentFirstResponder = textField;
    NSLog(@"textFieldDidBeginEditing");
}

- (void)doneWithKeyboard {
    NSString *fieldText = self.currentFirstResponder.text;
    [self.currentFirstResponder resignFirstResponder];
    self.currentFirstResponder = nil;
    [self.players replaceObjectAtIndex:0 withObject:fieldText];
}

Any insight into this problem would be appreciated.

链接地址: http://www.djcxy.com/p/44306.html

上一篇: 第一个响应者在编辑约束时辞职

下一篇: UITableViewCell中的UITextField将不接受becomeFirstResponder