Search code examples
iosswiftuitableviewcounteruibarbuttonitem

How to change badge number when button is pressed?


Ive been struggling to change the badge number in cartBtn when a count is placed and the atcbtn is pressed in the cells

right now what the CountVC is showing me in the cartBtn is the count of the cell when the atcbtn is pressed, but what im trying to do is get the overall count for every cell when the Atc btn is pressed

like say if my count is 4 in the first cell and my count is 3 in the second cell. the cartBtn should show 7 in the badge, instead of just the total for one cell in the badge if that makes any sense

struct Products {
    var name: String
    var count: Int
}

class CountViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var cartBtn: BadgeBarButtonItem!

    var productSetup: [Products] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self
    }

// changes the count on badge button but doesnt add up the count for every cell in the badege
//glitch is that it overloads the count passed into the cartVC when ATC is pressed multiple times in the cell
    @objc func cartCount(_ sender: UIButton){
        let currentCount = self.productSetup[sender.tag].count
        self.productSetup[sender.tag].count = currentCount + 1
        cartBtn.badgeNumber = currentCount
    }

    //increments the counter
    @objc func plusItem(_ sender: UIButton) {
        let currentCount = self.productSetup[sender.tag].count
        if currentCount > 9 {
            return
        }
        self.productSetup[sender.tag].count = currentCount + 1
        if let currentCell = self.tableView.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? ProductListCell {
            currentCell.lblQty.text = "\(self.productSetup[sender.tag].count)"
        }
    }

    // decrements the counter
    @objc func minusItem(_ sender: UIButton) {
        let currentCount = self.productSetup[sender.tag].count
        if !(currentCount - 1 >= 0) {
            return
        }
        self.productSetup[sender.tag].count = currentCount - 1
        if let currentCell = self.tableView.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? ProductListCell {
            currentCell.lblQty.text = "\(self.productSetup[sender.tag].count)"
        }
    }
}

extension CountViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return productSetup.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CountCell") as? CountCell else { return UITableViewCell() }

        // Allows increment and decrement to work in individual cells
        cell.lblQty.text = "\(self.productSetup[indexPath.row].count)"
        cell.plusBtn.tag = indexPath.row
        cell.minusBtn.tag = indexPath.row
        cell.plusBtn.addTarget(self, action: #selector(self.plusItem(_:)), for: .touchUpInside)
        cell.minusBtn.addTarget(self, action: #selector(self.minusItem(_:)), for: .touchUpInside)


        // used to change count in cart btn
        cell.atcBtn.tag = indexPath.row
        cell.atcBtn.addTarget(self, action: #selector(self.cartCount(_:)), for: .touchUpInside)     

        return cell
    }

}


Solution

  • You need to change your code to iterate over all the products to come up with a total:

    @objc func cartCount(_ sender: UIButton){
        var totalCount = 0
        for product in productSetup {
            totalCount += product.count
        }
    
        cartBtn.badgeNumber = totalCount
    
    }
    

    You can also do this as a one-liner, but it is a little less obvious what is going on if you aren't a Swift expert; It is up to you whether you prefer less code or easier to understand code for less experienced programmers:

    @objc func cartCount(_ sender: UIButton){
        cartBtn.badgeNumber = productSetup.map({$0.count}).reduce(0,+)
    }