I have a collection view inside a table view. There are two plus minus buttons in collection view cell. Now i have to update a label on the plus minus buttons action which is outside of table view. Thanks in advance.
I have to update a Slot: (label) by clicking on plus minus button.
I tried something like this with the delegate protocol.
I declare a delegate in my collection view class.
protocol SlotsCollectionViewCellDelegate: NSObjectProtocol {
func didTapOnIncrement(Int: Int)
func didTapOnDecrement(Int: Int)
}
//after that,
var delegate: SlotsCollectionViewCellDelegate?
@IBAction func plusBtnAction(_ sender: Any) {
self.delegate?.didTapOnIncrement(Int: cartCount)
}
@IBAction func minusBtnAction(_ sender: Any) {
delegate?.didTapOnDecrement(cell: self)
}
And in my Main View Controller
extension MainViewController: SlotsCollectionViewCellDelegate {
func didTapOnIncrement(Int: Int) {
cartSlot_lbl.text = Int.description
}
func didTapOnDecrement(Int: Int) {
cartSlot_lbl.text = Int.description
}
}
If I understood correctly, each time you push + or - you want to update slot label. In my opinion the easiest and fastest way to achieve this it's using NotificationCenter.default.post
In your collection view cell on button action write:
NotificationCenter.default.post(name: Notification.Name("postAction"), object: numberToIncreaseOrDecrease)
In your MainViewController where you have the slot label, add this code in view did load:
NotificationCenter.default.addObserver(self, selector: #selector(updateSlotValue(_:)), name: NSNotification.Name("postAction"), object: nil)
And out from the view did load add this function:
@objc func updateSlotValue(_ notification: Notification) {
let value = notification.object as! Int
cartSlot_lbl.text.text = value
}