resignFirstResponder to UITextViews on UITableViewCells that are no longer on screen

你说的曾经没有我的故事 提交于 2019-12-11 00:53:56

问题


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];


来源:https://stackoverflow.com/questions/5000785/resignfirstresponder-to-uitextviews-on-uitableviewcells-that-are-no-longer-on-sc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!