Search code examples
swiftprotocolsdelegation

Swift Delegation - Use Stepper in Tableview Cell to Update Label in Separate Class


I've been looking around stackoverflow a lot and reading a lot of different questions related to delegation but I haven't been able to work my problem out yet. I am trying to have my stepperAction (which is inside of a tableview cell) change a label in my BuyStats class every time its clicked. But so far, clicking the stepper has no effect. I think I need something in BuyStats.viewDidLoad() to set the delegate somehow but I'm not getting it. This may be easy for someone. Thanks for any help.

protocol SetRemainingValue : class {
func setValue(amount: Double)
}
}

//

class BuyStatsCell: UITableViewCell{

weak var setRemaining : SetRemainingValue?

@IBAction func stepperAction(_ sender: UIStepper) {

    setRemaining?.setValue(amount: sender.value)
}

//

class BuyStats: UIViewController, SetRemainingValue {

   @IBOutlet weak var spendAmount: UILabel!

override func viewDidLoad(){

}

 func setValue(amount: Double) {

    spendAmount.text = amount

}

}


Solution

  • If you are using a dynamic UITableView, you might try the following inside your cellForRowAtIndexPath:

    1. When you init your cell with dequeueCellWithReuseIdentifier, cast it as a BuyStatsCell (maybe with as! BuyStatsCell) to get access to its class variables.
    2. Set up the delegation with cell.setRemaining = self. The use of self assumes that your tableView's cellForRowAtIndexPath is inside the BuyStats viewController class. If it's not, you would want to get the reference for your BuyStats object in the class where your tableView's code lives, and use that reference in place of self, like cell.setRemaining = /*yourBuyStatsObjectReferenceGoesHere*/.

    Hope that helps.