項(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:willSelectRowAtIndexPath、tableView: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