淺析 iOS tableview 的 selectRowAtIndexPath 無效(默認(rèn)選中cell無效)

可能很多人都遇到過這種情況:

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];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容