Search code examples
iosiphoneuitableviewswift3

Swift 3.0 multiple selection with select all cell


I have added data in table view and I have manually added "select all" option to the list at first position, now when the user selects the first option which is 'select all' then the person manually option "Select all" is not selected. Select all, click then work all person or deselect working but signal selection all the person not working "Select all" I have tried the code below but it's not working so can any one help me to solve this?

enter image description here

var unchecked:Bool = true
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            // create a new cell if needed or reuse an old one
            let cell = ObjTableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SelectUserCell
            // set the text from the data model
             cell.selectionStyle = UITableViewCellSelectionStyle.none
            cell.lblStudentName.text = getStudentName[indexPath.row]

            if UnAll == "unselect" {
                if indexPath.row == 0 {
                    cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)

                }
                if indexPath.row == Int(selectedNumber) {
                    cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)

                }
                if indexPath.row == Int(unSelectNumber) {
                    //var j = "\(i)"

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

                }

            }else
            {
            if(unchecked){

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

            }
            else{

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

              }
            }

            return cell
        }
        var UnAll = ""
        var selectedNumber = ""
        var unSelectNumber = ""
        var checkselect:Bool = true

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

            UnAll.removeAll()
            selectedNumber.removeAll()
            unSelectNumber.removeAll()
            if(indexPath.row == 0){

                btnCheckBoxClick(sender: UIButton())

            }else
            {
            UnAll = "unselect"
                btnCheckBoxClick(sender: UIButton())
                if checkselect {
                    selectedNumber = "\(indexPath.row)"
                    checkselect = false
                }else
                {
                  unSelectNumber = "\(indexPath.row)"
                    checkselect = true
                }

                print("the selected index is : \(indexPath.row)")
            }

        }

        @IBAction func btnCheckBoxClick(_ sender: Any) {   

            if(unchecked){

                unchecked = false
            }
            else{              
                unchecked = true
            }
            ObjTableview.reloadData()
         }

Solution

  • Create a struct for model data with a Bool property. You can modify this property by cell selection.

    simulator

    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
      var allCharacters:[Character] = []
    
      override func viewDidLoad() {
        super.viewDidLoad()
            allCharacters = [Character(name: "All"),Character(name: "Luke Skywalker"),Character(name: "Leia Organa"),Character(name: "Advik Shah"),Character(name: "Aarav Modi")]
    
      }
      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allCharacters.count
      }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
        if cell == nil{
          cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
        }
          cell?.textLabel?.text = allCharacters[indexPath.row].name
          if allCharacters[indexPath.row].isSelected
          {
            cell?.accessoryType = .checkmark
          }
          else
          {
            cell?.accessoryType = .none
          }
          cell?.selectionStyle = .none
        return cell!
      }
      func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0
        {
          allCharacters[indexPath.row].isSelected = !allCharacters[indexPath.row].isSelected
          for index in allCharacters.indices
          {
            allCharacters[index].isSelected = allCharacters[indexPath.row].isSelected
          }
        }
        else
        {
          allCharacters[indexPath.row].isSelected = !allCharacters[indexPath.row].isSelected
          if allCharacters.dropFirst().filter({ $0.isSelected }).count == allCharacters.dropFirst().count
          {
            allCharacters[0].isSelected = true
          }
          else
          {
            allCharacters[0].isSelected = false
          }
        }
        tableView.reloadData()
      }
    
    
    
    
    }
    
    struct Character
    {
      var name:String
      //  var otherDetails
      var isSelected:Bool! = false
      init(name:String) {
        self.name = name
      }
    }
    

    Creating Array of Struct objects from array of dictionary

    let SubjectArray = json["students"] as! [[String:Any]]
    allCharacters = SubjectArray.map({ Character(name: $0["studentName"] as! String) })
    allCharacters.insert(Character(name:"All"), at: 0)