可能很多人都遇到過這種情況:
tableview列表,有時(shí)加載完,需要默認(rèn)選中某一行,給予選中效果;或者需要執(zhí)行某行的點(diǎn)擊事件。
我們舉例:
eg:比如我想默認(rèn)選中第一行
可能很多人,第一個(gè)想法就是這樣:
[mytableview selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
然而,你會(huì)發(fā)現(xiàn),如果你真的這樣寫了,有時(shí)候往往是沒有效果的,然后就一臉萌比了。。。
其實(shí),我們執(zhí)行這句話后,并不會(huì)走到tableview的didSelectRowAtIndexPath代理事件內(nèi),所以期望的效果肯定是沒有的,那這句話做了什么呢?
答案就是:
執(zhí)行這句話后, tableview會(huì)選中cell,只不過會(huì)執(zhí)行cell內(nèi)的一個(gè)setSelected自帶方法,如果你正好在這里面做了點(diǎn)擊效果處理,那么恭喜你,你是不會(huì)受影響的。
但是,如果你要做的是多選效果、或者你要的默認(rèn)選中,是需要執(zhí)行didSelectRowAtIndexPath內(nèi)部邏輯效果時(shí),悲劇的你會(huì)發(fā)現(xiàn)無效了。。。
那么,如果我們想達(dá)到我們的目的,該怎么做呢?
可以通過下面這樣:
//默認(rèn)選中第一行,并執(zhí)行點(diǎn)擊事件
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處理,就能達(dá)到你要的目的了
另:
//去除cell中間默認(rèn)的分割線
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
補(bǔ)充:(cell刷新問題)
/**
* 單個(gè)cell的刷新
*/
//1.當(dāng)前所要刷新的cell,傳入要刷新的 行數(shù) 和 組數(shù)
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//2.將indexPath添加到數(shù)組
NSArray <NSIndexPath *> *indexPathArray = @[indexPath];
//3.傳入數(shù)組,對(duì)當(dāng)前cell進(jìn)行刷新
[tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
/**
* 單個(gè)Section的刷新
*/
//1.傳入要刷新的組數(shù)
NSIndexSet *indexSet=[[NSIndexSet alloc] initWithIndex:0];
//2.傳入NSIndexSet進(jìn)行刷新
[tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];