UITableViewCell checkmark to be toggled on and off when tapped

前端 未结 14 1468
执念已碎
执念已碎 2020-11-30 22:25

I\'m working on a tableview

I want to be able to tap on each cell and when tapped, it displays a checkmark on the cell

Now I have some code that makes this w

14条回答
  •  长情又很酷
    2020-11-30 22:56

    Swift 4.0, all together now:

    import UIKit
    
    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var yourData = ["Cool","Sweet","Awesome"]
    
    var checked = [Bool]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        checked = Array(repeating: false, count: yourData.count)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return searchData.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt IndexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
    
        //configure you cell here.
        if checked[IndexPath.row] == false{
            cell.accessoryType = .none
        } else if checked[IndexPath.row] {
            cell.accessoryType = .checkmark
        }
    
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    
        if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
            if cell.accessoryType == .checkmark {
                cell.accessoryType = .none
                checked[indexPath.row] = false
            } else {
                cell.accessoryType = .checkmark
                checked[indexPath.row] = true
            }
        }
    }
    

    }

提交回复
热议问题