도래울

swift uitableview checkbox example 본문

개발/iOS

swift uitableview checkbox example

도래울 2016. 7. 13. 08:56

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
            }
       }
   }
}


'개발 > iOS' 카테고리의 다른 글

remove all subviews of a view in Swift  (0) 2016.07.13
swift for in loop  (0) 2016.07.13
Swift string replace  (0) 2016.07.12
Swift 배열과 딕셔너리  (0) 2016.07.12
[Swift] NSDateFormatter로 NSDate와 문자열 한국 날짜포맷 생성  (0) 2016.07.08
Comments