0

I'm having difficulty trying to add a UIBarButtonItem with title "Next(#)" where # is a dynamic counter that counts the number of cells selected in the table view as the user is selecting them. The array that tracks the cell selections is built and working properly however the count isn't getting updated; print lines in the console work as expected. My intent later is to only show the "(#)" when the count is greater than zero but right now I'm focused on just getting the count to update after each cell gets selected/deselected.

override func viewWillAppear(_ animated: Bool) {

    let barButtonCounter = "(\(invitedContacts.count))"
    let barButtonItemText = "Next\(barButtonCounter)"

    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "\(barButtonItemText)", style: .done, target: self, action: nil)
}

This is the closest SO thread I could find but from what I can tell it's not exactly doing what I want, at least visual design-wise but maybe totally and is written in Obj-C which I don't fully comprehend as I'm new to swift. My preference would be to build this natively without importing a library.

akash23a
  • 127
  • 10

2 Answers2

1

try with this lines

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  //your code for your counter
   self.navigationItem.rightBarButtonItem = nil
   let barButtonCounter = "(\(invitedContacts.count))"
   let barButtonItemText = "Next\(barButtonCounter)"

   navigationItem.rightBarButtonItem = UIBarButtonItem(title: "\(barButtonItemText)", style: .done, target: self, action: nil)
}
Andres Gomez
  • 458
  • 3
  • 12
  • This is it! And the same goes for the didSelectRowAt to account for the other use case. Waiting the 5 minutes to accept this answer – akash23a Jan 10 '20 at 03:43
  • This solution is incomplete and also bad practice to put configuration code that could be reusable inside another method – javier rivarola Jan 10 '20 at 03:53
0

You are only calling it once in viewWillAppear, i recommend you create a private function that takes as parameter the new count and updates the button, and you call that in every didSelect and didDeselect delegate methods from the tableView

javier rivarola
  • 500
  • 3
  • 6