-->

resignFirstResponder to UITextViews on UITableView

2019-07-21 08:01发布

问题:

I have a UITableView with a whole bunch of custom UITableViewCells in it. Each of these UITableViewCells has a UITextView in them.

The problem I'm having, is that if the user touches a UITextView, that becomes the firstResponder and the keyboard pops up. If the user then scrolls down to a point where the UITableViewCell that the firstResponder is on is no longer on the screen, I can't get at the UITextView to dismiss it.

I've tried holding (and retaining) a reference to the UITextView, but as soon as it leaves the screen and I try to access it I get an EXC_BAD_ACCESS. This happens no matter how many times I retain it, so I suspect it may be having dealloc called directly on it (I'm not sure how the cell dequeueing system actually works).

The other weird thing is that if I scroll the UITextField off screen, the keyboard can still be used to write to it, and the text typed is visible when I scroll back to the UITextField.

Any help would be much appreciated.

回答1:

Fluchtpunkt was absolutely correct, I wasn't re-using my cells correctly. My problem was that I was loading my custom UITableViewCells from a nib using the method:

static NSString *CellIdentifier = @"CustomCell";
ExpandingTableViewCell *cell = (ExpandingTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ExpandingTableViewCell" owner:self options:nil];
    cell = (ExpandingTableViewCell *)[nib objectAtIndex:0];
}

I didn't realize that I had to set the Identifier field in the .xib file for the custom cell to CustomCell. As soon as my cells were being re-used properly, the problem with the UITextField being dealloc'd before its time disappeared.



回答2:

You can save the indexPath of the cell that user is editing. Then when he scrolls test if that cell is in visible cells of the tableView. If not get the text field from that cell and dismiss the keyboard.

UITableViewCell *editingCell =  [self.tableView cellForRowAtIndexPath:SavedIndexPath];
[editingCell.textField resignFirstResponder];