简体   繁体   中英

Get all tableview cells with accessory type checkmark

I want to get all the selected values in the tableview.

For Example:

// I'm unable to loop through the tableview (myTableView.cells is not valid)
func saveClicked(sender:AnyObject)
{
 let testArray = NSMutableArray()

  for i in myTableView.cells
  {
    if (i.accessorytype = .CheckMark)
    {
      testArray.addObject(i)
    }
  }
}

Here is a simplified example. Set up your array of items, myItemsArray and give it a isChecked property that is a bool . Then in your didSelectRow method, you toggle the isChecked value to true or false accordingly. Then when you want to find which "cells", technically items in myItemsArray , have a value of true you can iterate thru the array as shown below. let me know if this is unclear please.

var myItemsArray = [Items]()
var checkedItemsArray = [Items]()

override func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
    if cell.accessoryType == .Checkmark {
        cell.accesoryType == .None
        myItemsArray[indexPath.row].isChecked == false
    } else if cell.accessoryType == .None {
        cell.accesoryType = .Checkmark
        myItemsArray[indexPath.row].isChecked == true
    }
}

  func saveClicked(){
    myItemsArray.removeAll()

    for i in 0...myItemsArray.count-1 {
        if myItemsArray[i].isChecked == true{
            checkedItemsArray.append(myItemsArray[i])
        }
    }
}
  1. IT you want default checkmark for tableview cell then Add

cell.accessoryType = .Checkmark

in "cellForRowAtIndexPath" delegate method

  1. If you want checkmark on selection of rows then add

override func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ if cell.accessoryType == .Checkmark { cell.accesoryType == .None } else if cell.accessoryType == .None { cell.accesoryType = .Checkmark } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM