我給你換背景你的細胞如何顏色的例子並選擇最初的一,這樣你就可以遵循,把你需要的代碼:
在你UIViewController
子類,實現這些方法,所以你可以把你的邏輯選擇和取消選擇狀態:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath)!
selectedCell.backgroundColor = UIColor.purple
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let deselectedCell = tableView.cellForRow(at: indexPath)!
deselectedCell.backgroundColor = UIColor.clear
}
在您的自定義UITableViewCell
子類必須重寫isSelected
財產,這是爲了避免方法tableView.selectRow:atIndexPath
繞過didSelect
關鍵:
class CustomTableViewCell: UITableViewCell {
override var isSelected: Bool {
didSet {
print(isSelected.description)
self.selectionStyle = .none
if isSelected{
self.backgroundColor = UIColor.purple
} else {
self.backgroundColor = UIColor.clear
}
}
}
}
最後,回到你的UIViewController
子類,你可以調用selectRow:atIndexPath
在viewDidLoad
方法,例如:
override func viewDidLoad(){
super.viewDidLoad()
tableView.selectRow(at: IndexPath(row: 0, section: 0) , animated: true, scrollPosition: UITableViewScrollPosition.none)
}
感謝您的回答,亞歷山大。然而問題是''tableView.selectRow(at:IndexPath(row:0,section:0),animated:true,scrollPosition:UITableViewScrollPosition.none)''跳過'willSelect'和'didSelect'按照文檔 –
@ZackShapiro是的,它跳過。這就是爲什麼我創建了一個自定義的'UITableViewCell'和overrided'isSelected'屬性,你可以把它放在你的邏輯中,所以當你調用'tableView.selectRow(at :)' –
啊,我錯過了那部分不會被繞過。我的錯。我會試一試。謝謝! –