可能很多人都遇到过这种情况:
tableview列表,有时加载完,需要默认选中某一行,给予选中效果;或者需要执行某行的点击事件。
我们举例:
eg:比如我想默认选中第一行
可能很多人,第一个想法就是这样:
[mytableview selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
然而,你会发现,如果你真的这样写了,有时候往往是没有效果的,然后就一脸萌比了。。。
其实,我们执行这句话后,并不会走到tableview的didSelectRowAtIndexPath代理事件内,所以期望的效果肯定是没有的,那这句话做了什么呢?
答案就是:
执行这句话后, tableview会选中cell,只不过会执行cell内的一个setSelected自带方法,如果你正好在这里面做了点击效果处理,那么恭喜你,你是不会受影响的。
但是,如果你要做的是多选效果、或者你要的默认选中,是需要执行didSelectRowAtIndexPath内部逻辑效果时,悲剧的你会发现无效了。。。
那么,如果我们想达到我们的目的,该怎么做呢?
可以通过下面这样:
//默认选中第一行,并执行点击事件 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [mytableview selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop]; if ([mytableview.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) { [mytableview.delegate tableView:mytableview didSelectRowAtIndexPath:indexPath]; }
在后面,添加一句delegate处理,就能达到你要的目的了
??
浅析iOS tableview的selectRowAtIndexPath无效(默认选中cell无效)
原文:http://www.cnblogs.com/yajunLi/p/6293052.html