Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add or remove objects from an array based on didSelectRowAtIndexpath in Swift 3

I am working on expandable tableView where I need to add or remove the objects based on didSelectRowAtIndexpath. I was able to add the selected item into an array but the problem is when I am trying to remove the selection from array.

This is the error I am getting:

cannot invoke index with an argument list of type (of:any)

Here is my code:

func expandableTableView(_ expandableTableView: LUExpandableTableView, didSelectRowAt indexPath: IndexPath) {
    let selectedService = arrData[indexPath.section].Children?[indexPath.row].EnglishName ?? ""
    let inPrice = arrData[indexPath.section].Children?[indexPath.row].InPrice ?? 0

    print("service and price : \(selectedService) \(inPrice)")

    let selectedItem = (" \(selectedService) \(inPrice)")
    let cell: UITableViewCell? = expandableTableView.cellForRow(at: indexPath)

    if cell?.accessoryType == UITableViewCellAccessoryType.none
    {
        cell?.accessoryType = UITableViewCellAccessoryType.checkmark
        selectionArr.append(selectedItem)
    }
    else
    {
        cell?.accessoryType = UITableViewCellAccessoryType.none
        selectionArr.remove(at: selectionArr.index(of: selectedItem)!)
    }

    print(selectionArr)
}
like image 320
mtech ac Avatar asked Jul 22 '26 09:07

mtech ac


1 Answers

@AnhPham

Hey, Tried modifying your code and it worked well please go through following for adding item in array and removing from the same on tableview's didselect and diddeselect methods respectively.

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

    let categoryTableCell = self.categoriesTableview.cellForRow(at: indexPath) as! CategoriesTableCell

    self.tempCategories.append(self.categories[indexPath.row])

    print("tempArray select:\(self.tempCategories)")

}

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

    let categoryTableCell = self.categoriesTableview.cellForRow(at: indexPath) as! CategoriesTableCell

    self.tempCategories.remove(at: self.tempCategories.index(of:self.categories[indexPath.row])!)

    print("tempArray deselect:\(self.tempCategories)")

}
like image 138
Fatin Wasta Avatar answered Jul 24 '26 01:07

Fatin Wasta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!