Swift 3.0 multiple selection with select all cell

前端 未结 4 1985
心在旅途
心在旅途 2020-12-10 16:58

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 a

4条回答
  •  一生所求
    2020-12-10 17:19

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

    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)
    

提交回复
热议问题