Swift 3.0 with Select All

I added the data to the table view, and I manually added “select all” to the list in the first position now that the user selects the first option, which selects everything, and then all the elements in the list should be selected and deselected when you select one and the same same, I tried the code below, but it doesn’t work, so someone can help me solve this problem.

 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
        }
}
+4
source share
1 answer

Jayprakash, you're almost there. You need to change 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 this will simplify your code structure.

+1
source

Source: https://habr.com/ru/post/1686319/


All Articles