swift 如何在ViewController导航标题上显示从tableView单元格中选择的若干项?

anauzrmj  于 2022-12-10  发布在  Swift
关注(0)|答案(1)|浏览(134)

我试图在ViewController的标题导航栏上显示从TableView单元格的UI按钮中选择的项目数。但是它工作正常,您必须退出屏幕并返回以查看选择的项目数。我如何解决这个问题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
    
    }
nwlqm0z1

nwlqm0z11#

您可以将NavigationTitle更新方法移动到selectDealerButton操作中,它将在您每次选择或取消选择经销商时更新标题。

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

}

相关问题