Swift 3.0 multiple selection with whole cell selection

I added the data in the form of tables, and I manually added “select all” to the list in the first position now that the user selects the first option, which selects everything except the person manually. Select All is not selected. select all the clicks, then follow all the steps or deselect the job, but select the signal for the whole person who doesn’t work “Select all”, I tried the code below, but it doesn’t work, so someone can help me solve this problem.

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()
         }
+4
source share
4 answers

Create a model data structure using the Bool property. You can change this property by selecting a cell.

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 an array of Struct objects from a dictionary array

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

, . , ( ), . " ", , .

// MARK: -  struct for cell item
    struct CellItem {
    var name : String
    var isSelected:Bool! = false
    init(name: String) {
           self.name = name
         }
    }

class ViewController: UITableViewController {

@IBOutlet var viewTable: UITableView!
// Declare a boolean varaible to toggle the checkbox in the first section of table view
var isSelectAllSelected : Bool = false
var cellData: [CellItem] = []

override func viewDidLoad() {
    super.viewDidLoad()
    cellData = [CellItem(name: "Luke Skywalker"),CellItem(name: "Leia Organa"),CellItem(name: "Advik Shah"),CellItem(name: "Aarav Modi")]
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
         return 1
    }
    else
    {
        return cellData.count
    }
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 0
}

// MARK: -  Table view delegates

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 60

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = TableCell()
    cell.selectionStyle = .none

    if indexPath.section == 0 {
        cell.textLabel?.text = "Select All"
        if isSelectAllSelected{
            cell.accessoryType = .checkmark
        }
        else{
            cell.accessoryType = .none
        }

    }
    else
    {
        cell.textLabel?.text = cellData[indexPath.row].name
        if cellData[indexPath.row].isSelected{
            cell.accessoryType = .checkmark
        }
        else{
            cell.accessoryType = .none
        }

    }
    return cell
}


override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.section == 0
    {
        cellData[indexPath.row].isSelected = !cellData[indexPath.row].isSelected
        isSelectAllSelected = cellData[indexPath.row].isSelected
        for index in cellData.indices
        {
            cellData[index].isSelected = cellData[indexPath.row].isSelected
        }
    }
    else
    {
        cellData[indexPath.row].isSelected = !cellData[indexPath.row].isSelected
        if cellData.filter({ $0.isSelected }).count == cellData.count
        {
            isSelectAllSelected = true
        }
        else
        {
            isSelectAllSelected = false
        }

    }
    viewTable.reloadData()
} }
+3

, cheboxbutton addtarget indexpath.row, . .

class ViewController:UIViewController,UITableViewDelegate,UITableViewDataSource {

@IBOutlet weak var ObjTableview: UITableView!
var arrStudent = ["1","2","3","4","5"]
var arrSelectedStudent :[Int] = []
var selectAll:Bool = false

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


//MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrStudent.count
}

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]
    cell.lblStudentName.text = arrStudent[indexPath.row]
    cell.btnCheckbox.tag = indexPath.row
   cell.btnCheckbox.addTarget(self, action:#selector(btnCheckBoxClick(sender:)), for: .touchUpInside)


    if selectAll {
        cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
    }else{
    if arrSelectedStudent.contains(indexPath.row){
        cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
    }else{
        cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
    }
    }

         return cell
}


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

func btnCheckBoxClick(sender: UIButton) {
    if sender.tag == 0{
        selectAll = true
    }else
    {
        selectAll = false
    if let index = arrSelectedStudent.index(of: sender.tag) {
        arrSelectedStudent.remove(at: index)
    }else{
        arrSelectedStudent.append(sender.tag)
    }
    }

    ObjTableview.reloadData()
}}
+2

@Pranil "", .

NSMutableIndexSet . , - . , , , tableview , .

Here is my implementation. The “all” state is determined by the number of selected rows equal to the number of rows in the data source array.

I just used simple desktop accessories for checkmarks, but I'm sure you can see how to take an image-based approach in cellForRow(at:)

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableview: UITableView!


    let names: [String]? = ["Luke Skywalker","Leia Organa","Advik Shah","Aarav Modi"]

    var selectedRows = NSMutableIndexSet()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func numberOfSections(in tableView: UITableView) -> Int {

        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        guard let names = self.names else {
            return 0
        }

        return 0 == section ? 1 : names.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        var text: String
        var accessory = UITableViewCellAccessoryType.none

        if 0 == indexPath.section {
            text = "All"
            if self.selectedRows.count == self.names!.count {
                accessory = .checkmark
            }
        } else {
            text = names![indexPath.row]
            if selectedRows.contains(indexPath.row) {
                accessory = .checkmark
            }
        }

        cell.textLabel!.text = text
        cell.accessoryType = accessory

        return cell
    }

    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        if indexPath.section == 0 {
            if self.selectedRows.count == self.names!.count {
                self.selectedRows = NSMutableIndexSet()
            } else {
                self.selectedRows = NSMutableIndexSet(indexesIn: NSRange(location: 0, length: self.names!.count))
            }
            tableView.reloadData()
        } else {
            self.selectedRows.contains(indexPath.row) ? self.selectedRows.remove(indexPath.row) : self.selectedRows.add(indexPath.row)

            let rows = [IndexPath(row: 0, section: 0), indexPath]

            tableView.reloadRows(at: rows, with: .none)
        }
        return nil
    }
}
+2
source

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


All Articles