本文主要介绍如何正确实现 TableView 的单选和反选.

遇到一个需求是要实现一个单选列表, 且每个选项都可以进行反选操作. 使用 TableView 或 CollectionView 均可直接实现单选, 但如果要对一个 cell 进行反选, 就还需要处理一下, 核心代码如下:

swift
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    var resultIndexPath: IndexPath? = nil
    if let selectedIndex = tableView.indexPathForSelectedRow,
        selectedIndex == indexPath {
        // 反选
        tableView.deselectRow(at: indexPath, animated: false)
    } else {
        resultIndexPath = indexPath
    }
    presenter?.setCurrentSelectedIndexPath(resultIndexPath)
    return resultIndexPath
}

这段代码的功能介绍: 在准备选中某个 cell 时, 先判断其是否被选中, 如果没有, 则返回它的 indexPath, 否则对其执行反选, 并返回 nil.

这样就保证了 cell 不但可以单选, 且可以被反选.

在 cell 的实现中, 只需要类似下面这样处理, 就可以在显示上表征该 cell 是否被选中了:

swift
override func setSelected(_ selected: Bool, animated: Bool) {
	// 在 cell 中布局了一个 circleIndicator 视图, 改变它的背景色来标志 cell 是否被选中.
    if selected {
        circleIndicator.backgroundColor = ColorConfigs.Registration.redColor
    } else {
        circleIndicator.backgroundColor = .clear
    }
}