Search code examples
arraysswiftbuttontableview

Unable to remove tableview's deselected row array value in Swift


I am using tableview for multiple row selection with checkmark using button. with this code able to add all selected row ids in arrSelectedRows and able to remove when deselect.... but here i am adding all selected row JSON title in arrSubCat and not able to remove

code: in this code arrSubCat is array of strings.. in this array i am adding selected row JSON title.. here the issue is if i deselect the row then unable to remove deselected row title from arrSubCat array

if i try like this arrSubCat.remove(at: (sender.tag))

then error:

Fatal error: Index out of range

how to solve this issue.. please do guide

 var arrSelectedRows:[Int] = []
 var arrSubCat:[String] = []

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return getSubCategory?.result?.sub_categories?.count ?? 0
}
var removeIndex: Int?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 
 let cell = tableView.dequeueReusableCell(withIdentifier: "EditLangTableVIewCell", for: indexPath) as! EditLangTableVIewCell

 let id = getSubCategory?.result?.sub_categories?[indexPath.row].id ?? 0

 if arrSelectedRows.contains(id){
     cell.langSelectButn.setImage(UIImage(systemName: "checkmark"), for: .normal)

 }else{
     cell.langSelectButn.setImage(UIImage(named: "checkbox_inactive"), for: .normal)
}
 cell.langSelectButn.tag = id
 cell.langSelectButn.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.firstIndex(of: sender.tag)!)
    arrSubCat.remove(at: (sender.tag))

}else{
    
    self.arrSelectedRows.append(sender.tag)
    print("arrayof selected row ids \(arrSelectedRows)")
    if let selectedSubcat = getSubCategory?.result?.sub_categories{
        for singleSubcat in selectedSubcat{
            if sender.tag == singleSubcat.id{
            arrSubCat.append(singleSubcat.title ?? "")
            }
        }
    }
    print("array of subcat title \(arrSubCat)")
}
self.tableView.reloadData()

}

Solution

  • Modify the code of checkBoxSelection() method like below

    if self.arrSelectedRows.contains(sender.tag){
        if let selectedIndex = self.arrSelectedRows.firstIndex(of: sender.tag) {
            self.arrSelectedRows.remove(at: selectedIndex)
            arrSubCat.remove(at: selectedIndex)
        }
    }