Blackroche
Blackroche

Reputation: 67

Uibuttons inside a custom uitableviewcell

I have 2 buttons inside my custom UITableViewCell, one to add x1 quantity of the item already chosen and the other to subtract x1. How can i set the IBAction for the buttons within the custom class to be able to modify elements within the entire page and modify values inside my View Controller class? What would be the best way to approach this?enter image description here

I have attached an image of my storyboard.

Upvotes: 0

Views: 222

Answers (2)

Fangming
Fangming

Reputation: 25260

In your cellForRow function, add button listener in this way

cell.plusBtn.addTarget(self, action: "plusBtnClicked:", for: .touchUpInside)
cell.minusBtn.addTarget(self, action: "minusBtnClicked:", for: .touchUpInside)

Then receive the call by

func plusBtnClicked(_ sender: AnyObject?) {
  score += 1
  self.tableView.reloadData()
}

func minusBtnClicked(_ sender: AnyObject?) {
  score -= 1
  self.tableView.reloadData()
}

Upvotes: 1

Jake T.
Jake T.

Reputation: 4378

You have several options.

One is to use the NSNotificationCenter. You can add whatever objects need the +1 / -1 alert as an observer to be alerted by updates to the quanitty that the table view cell knows.

Another is to programmatically add the action to the buttons with the VC as the target having its Selectors triggered, so the buttons aren't triggering an action on the TableViewCell, they're triggering an action directly on the objects that need to handle it, rather than those objects waiting for an indirect notification.

Upvotes: 0

Related Questions