iOS 代碼實(shí)現(xiàn)select tableView row

項(xiàng)目背景

在項(xiàng)目中經(jīng)常會(huì)有這樣的需求:打開列表要勾選用戶當(dāng)前選中的一項(xiàng)。這時(shí),就需要用代碼來(lái)選擇tableView的row了。

以下兩種方式都可以到達(dá)此效果:

方法一:

selectRowAtIndexPath
首先在代碼中實(shí)現(xiàn)selectRowAtIndexPath方法,接著在tableView的delegate中實(shí)現(xiàn)tableView:willDisplayCell
需要注意的是:selectRowAtIndexPath并不會(huì)走到tableView:willSelectRowAtIndexPathtableView:didSelectRowAtIndexPath、UITableViewSelectionDidChangeNotification代理方法中,所以要在tableView:willDisplayCell中實(shí)現(xiàn)選中效果

實(shí)例代碼:

// 選中第x項(xiàng)
tableView.selectRow(at: IndexPath(row: x, section: 0), animated: false, scrollPosition: .none)
// 在delegate中修改選中項(xiàng)的樣式
extension DemoViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if cell.isSelected {
            // 實(shí)現(xiàn)選中效果
        }
    }
}

但有些場(chǎng)景下,tableView已經(jīng)繪制完成,方法一就不適用了,就需要用到

方法二:

直接調(diào)用tableView(tableView, didSelectRowAt: indexPath)

實(shí)例代碼:

// 選中第x項(xiàng)
tableView(tableView, didSelectRowAt: IndexPath(row: x, section: 0))
// 在delegate中修改選中項(xiàng)的樣式
extension DemoViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        for _ in 0...tableViewData.count - 1 {
            if (tableView.cellForRow(at: indexPath) as! DemoTableViewCell).isSelected {
                // 取消之前的選中樣式
            }
        }
        // 實(shí)現(xiàn)選中效果
    }
}

OC語(yǔ)言實(shí)現(xiàn)方式可以參考:

https://stackoverflow.com/questions/2035061/select-tableview-row-programmatically

最后編輯于
?著作權(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)容