在选中一个 swift 2 之前无法取消选中所有单元格

Can't un check all cell before check one swift 2

我正在使用 swift 2 和 UITableViews,当我按下一个单元格时,会出现一个复选标记,但我不希望在我的表格视图中只能选中一个单元格,这样其他复选标记就会从我的表格视图中消失.我尝试了不同的技术但没有成功。我有一个只有标签的 CustomCell。

这是我的代码:

import UIKit


class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
    @IBOutlet weak var tableView: UITableView!

    var answersList: [String] = ["One","Two","Three","Four","Five"]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return answersList.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("MyCustomCell", forIndexPath: indexPath) as! MyCustomCell
        cell.displayAnswers(answersList[indexPath.row]) // My cell is just a label       
        return cell
    }

    // Mark: Table View Delegate

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        // Element selected in one of the array list
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        if let cell = tableView.cellForRowAtIndexPath(indexPath) {
            if cell.accessoryType == .Checkmark {
                cell.accessoryType = .None
            } else {
                cell.accessoryType = .Checkmark
            }
        }
    }

}

假设您只有这一部分,这就是您可以做的

// checkmarks when tapped

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let section = indexPath.section
    let numberOfRows = tableView.numberOfRowsInSection(section)
    for row in 0..<numberOfRows {
        if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) {
            cell.accessoryType = row == indexPath.row ? .Checkmark : .None
        }
    }
}

来自@SirH 的固定代码可以与 Swift 3

一起使用
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)



    let section = indexPath.section
    let numberOfRows = tableView.numberOfRows(inSection: section)
    for row in 0..<numberOfRows {
        if let cell = tableView.cellForRow(at:IndexPath(row: row, section: section)) {
            cell.accessoryType = row == indexPath.row ? .checkmark : .none
        }
    }
}