偶然遇到UITableView的代理方法didDeselectRowAtIndexPath不响应。
项目中要实现选中表格某一行时,动画隐藏UITableView,同时取消选中上一次选中的行,即如下效果。
最初代码是这样写的:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
CountryCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.confirmImgView.hidden = NO;
//动画隐藏UITableView
[UIView animateWithDuration:0.3 animations:^{
CGRect frame = _tableView.frame;
frame.origin.y = Screen_Height;
_tableView.frame = frame;
}];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
CountryCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.confirmImgView.hidden = YES;
}
结果却没有到达预期效果,didDeselectRowAtIndexPath代理方法根本就没有触发,如下图:
无意中发现注释掉动画隐藏UITableView那段代码,就会触发didDeselectRowAtIndexPath代理方法,不知道为什么会这样。
只能用一种比较笨的方法实现:
加一个标记属性,初始值为-1:
_selRow = -1;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//找到上一次选中的行
if (_selRow >= 0) {
CountryCell* selCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:
_selRow inSection:0]];
selCell.confirmImgView.hidden = YES; //didDeselectRowAtIndexPath方法就不需要了
}
CountryCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.confirmImgView.hidden = NO;
_selRow = indexPath.row;
//动画隐藏UITableView
[UIView animateWithDuration:0.3 animations:^{
CGRect frame = _tableView.frame;
frame.origin.y = Screen_Height;
_tableView.frame = frame;
}];
}