I have tableview with custom check box. here if i click select all
button which is outside of tableview then i need to show all tableview rows selected with checkmark
code: tableview cell contains chkImg and chkBtn for row selection. with this code i can select and deselect multiple rows but if i click selectAllBtn
i need all rows selected with cell.chkImg.image = UIImage(systemName: "checkmark")
and all rows id in arrSelectedRows
how to do that please guid me
var arrSelectedRows:[Int] = []
@IBAction func selectAllBtn(_ sender: UIButton) {
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ServiceListTableViewCell.cellIdentifier, for: indexPath) as! ServiceListTableViewCell
let id = self.serviceList?.result?.services?[indexPath.row].id ?? 0
if arrSelectedRows.contains(id){
cell.chkImg.image = UIImage(systemName: "checkmark")
}else{
cell.chkImg.image = UIImage(named: "checkbox_inactive")
}
cell.chkBtn.tag = id
cell.chkBtn.addTarget(self, action: #selector(checkBoxSelection(_:)), for: .touchUpInside)
return cell
}
@objc func checkBoxSelection(_ sender:UIButton)
{
print(sender.tag)
if self.arrSelectedRows.contains(sender.tag){
self.arrSelectedRows.remove(at: self.arrSelectedRows.index(of: sender.tag)!)
print("arrayof selected row ids \(arrSelectedRows)")
}else{
self.arrSelectedRows.append(sender.tag)
}
self.tableView.reloadData()
}
You can use Swift map function, by it you get all ids in your selectedArray
@IBAction func selectAllBtn(_ sender: UIButton) {
let servicesCount = self.serviceList?.result?.services?.count ?? 0
if servicesCount == self.arrSelectedRows {
self.arrSelectedRows.removeAll()
} else {
self.arrSelectedRows = self.serviceList?.result?.services?.map({$0.id ?? 0})
}
tableView.reloadData()
}