Home > Blockchain >  How to display a number of selected items from a tableView Cell on a ViewController navigation title
How to display a number of selected items from a tableView Cell on a ViewController navigation title

Time:12-03

I am trying to display the number of selected items from a UIbuttton on Tableviewcell on the title nav on a ViewController . It works however you'd have to exit the screen and return back to see the number of selected items. How can I resolve this https://gifyu.com/image/Sh5gs

 class DealerCardTableViewCell: UITableViewCell {
        @IBOutlet weak var selectDealerButton: UIButton!
    
      var dealerCount = 0{
            didSet{
                dealerListDelegate?.didUpdateDealerCount(dealerCount: dealerCount)
            }
        }
    
       @objc func selectDealer() {
            guard let account = account else { return }
            
            selectDealerButton.isSelected = !selectDealerButton.isSelected
            dealerCount =selectDealerButton.isSelected ? 1 : -1
        }
    
    
    class DealerListViewController: DealerCardTableViewController {
    
       override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            didUpdateDealerCount(dealerCount: 0)
        }

    func didUpdateDealerCount(dealerCount: Int){
        navigationItem.title = "Selected Dealers - \(selectedAccounts.count   dealerCount)"
    }

 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            guard let cell = super.tableView(tableView, cellForRowAt: indexPath) as? DealerCardTableViewCell, accounts.count > 0 else { return UITableViewCell() }
    
                cell.delegate = self
    
    }

CodePudding user response:

You can move the NavigationTitle update method inside the selectDealerButton action and it will update title every time you select or deselect a dealer.

class DealerCardTableViewCell: UITableViewCell {
  @IBOutlet weak var selectDealerButton: UIButton!

  var dealerCount = 0

   @objc func selectDealer() {
        guard let account = account else { return }
        
        selectDealerButton.isSelected = !selectDealerButton.isSelected
        dealerCount =selectDealerButton.isSelected ? 1 : -1
        didUpdateDealerCount(dealerCount: dealerCount)
    }


class DealerListViewController: DealerCardTableViewController {

   override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

func didUpdateDealerCount(dealerCount: Int){
    navigationItem.title = "Selected Dealers - \(selectedAccounts.count   dealerCount)"
}



override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = super.tableView(tableView, cellForRowAt: indexPath) as? DealerCardTableViewCell, accounts.count > 0 else { return UITableViewCell() }

            cell.delegate = self

}
  • Related