0

我正在使用 swift 2 和 UITableViews,当我按下一个单元格时,会出现一个复选标记,但我不希望在我的 tableview 中只能检查一个单元格,因此其他复选标记将从我的 tableview 中消失。我尝试了不同的技术但没有成功。我有一个只有标签的 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
            }
        }
    }

}
4

2 回答 2

5

假设你只有这里的部分是你可以做的

// 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
        }
    }
}
于 2016-05-03T13:53:34.593 回答
0

修复了来自 @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
        }
    }
}
于 2017-03-16T08:25:43.583 回答