Я использую 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
            }
        }
    }

}
0
fandro 3 Май 2016 в 16:48

2 ответа

Лучший ответ

Предполагая, что у вас есть только раздел, вот что вы можете сделать

// 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
        }
    }
}
5
SirH 3 Май 2016 в 13:53

Исправлен код от @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
        }
    }
}
0
fandro 16 Мар 2017 в 09:23