UITableViewCell checkmark to be toggled on and off when tapped

前端 未结 14 1453
执念已碎
执念已碎 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:59

    Try this:

    var checked = [Bool]() // Have an array equal to the number of cells in your table
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
    
        //configure you cell here.
        if !checked[indexPath.row] {
            cell.accessoryType = .None
        } else if checked[indexPath.row] {
            cell.accessoryType = .Checkmark
        }
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if let cell = tableView.cellForRowAtIndexPath(indexPath) {
            if cell.accessoryType == .Checkmark {
                 cell.accessoryType = .None
                 checked[indexPath.row] = false
            } else {
                 cell.accessoryType = .Checkmark
                 checked[indexPath.row] = true
            }
        }    
    }
    

    To reset all the checkboxes:

    func resetChecks() {
       for i in 0.. < tableView.numberOfSections {
           for j in 0.. < tableView.numberOfRowsInSection(i) {
                if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) {
                   cell.accessoryType = .None
                }
           }
       }
    }
    

提交回复
热议问题