0

I have an application where I have two sections the issue I have now is if I select an item in section 1, it automatically selects a cell in section 2 which is not suppose to be. I want Items to be selectable in section 1 without affecting section two.

below is my selection

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.section {
        case 0:
            showCustomDialog(subD: sub[indexPath.row])

        case 1:
            let cell = tableView.cellForRow(at: indexPath) as! VasListCell
            cell.checkBox.setOn(true, animated: true)

        default: break
        }
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        switch indexPath.section {
        case 1:
            let cell = tableView.cellForRow(at: indexPath) as! VasListCell
            cell.checkBox.setOn(false, animated: true)

        default: break
        }

    }

where I am using the selected index

func selectedIndex(viewcontroller: UIViewController) {
        let selectedRows = tableView.indexPathsForSelectedRows
        guard let vasRow = selectedRows?.map ({ vas[$0.row] }) else { return }
        selectedVasData = vasRow
        let vasData = selectedVasData
        let subData = selectedSubData
        let vcr = viewcontroller as! CheckoutVC
        vcr.vas = vasData
        vcr.sub = subData
        let tot1 = subData.compactMap {$0.price}
        let tot2 = vasData.compactMap {$0.amount}

        let tot = tot1 + tot2

        let reduced = tot.compactMap(Double.init).reduce(0, +)
        vcr.tableView.reloadData()
        self.present(viewcontroller, animated: true, completion: nil)
        print("CELL INDEX vas \(StaticFunc.convertDoubleToCurrency(amount: reduced))")
    }
King
  • 1,885
  • 3
  • 27
  • 84
  • You are making a common mistake. You change the state of a cell in `did(De)selectRowAt` but you don't save the state. The next time the table view is reloaded the cells are reused and you have randomly selected cells. It's highly recommended to manipulate the view **only** in `cellForRow` and to keep the state of all UI elements in the data model.. To change a state, change the model and reload only the particular row. – vadian Jul 13 '19 at 16:20
  • I do not really understand this. Can you kindly show me code to illustrate? – King Jul 13 '19 at 16:22
  • Please look at https://stackoverflow.com/questions/55533938/i-want-to-set-tick-in-tableview-cell-for-row-at-indexpath/55535073#55535073 – vadian Jul 13 '19 at 16:26
  • But I have two different cells presented in the two sections and different models – King Jul 13 '19 at 16:28
  • It doesn't matter. It's just important to save the `selected` state in the data model. – vadian Jul 13 '19 at 16:29
  • it does not work for me. tried it – King Jul 13 '19 at 16:40

0 Answers0