swift 3.0 multiple selection with Select All option

Viewed 1767

i have added data in table view and i have manually added "select all" option in to list at first position now when user select first option which is select all then all item in to list should be selected and deselected when choose same. i have tried code below but its not working so can any one help me to solve this

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = ObjTableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SelectUserCell
    for i in 0 ..< self.getStudentName.count {
        cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
        print (i) //i will increment up one with each iteration of the for loop

    }

}
var unchecked = true
 @IBAction func btnCheckBoxClick(_ sender: Any) {

if unchecked == true {
           //(sender as AnyObject).setImage(UIImage(named: "selectedItem"), for: .normal)
            cell?.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
            //unchecked = false
            let cello = ObjTableview.cellForRow(at: indexPath!)
            print(cello!)
            ObjTableview.reloadData()
        }else
        {
            //(sender as AnyObject).setImage(UIImage(named: "unSelectedItem"), for: .normal)
            cell?.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
           // unchecked = true
        }
}
1 Answers

Jayprakash, You are almost there. You need to modify some lines -

Here is your modified code snippet

var unchecked:Bool = true

@IBAction func btnCheckBoxClick(_ sender: Any) {

    if(unchecked){

        unchecked = false
    }
    else{

        unchecked = true
    }


    ObjTableview.reloadData()


}



func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if(indexPath.row == 0){

            btnCheckBoxClick(sender: UIButton())

      }

 }


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{

        let cell : SelectUserCell!
        cell = tableView .dequeueReusableCell(withIdentifier: "SelectUserCell", for: indexPath) as! SelectUserCell
        cell.selectionStyle = UITableViewCellSelectionStyle.none


       if(unchecked){

              cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)

         }
       else{

              cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
         }


   // Do your stuff here

   return cell
}

Hop it will simplify your code structure.

Related