swifttableviewuistepper

Swift - Increment Label with Stepper in TableView Cell


Another Swift beginner here. I simply want a Stepper in each of my TableView cells that increments a label in the same cell.

I have found a couple of questions on this topic, but they include other elements and I haven't been able to extract the basic concept.

Swift Stepper Action that changes UITextField and UILabel within same cell

Stepper on tableview cell (swift)

So far I have connected IBOutlets for my Label and Stepper, as well as an IBAction for my Stepper in my cell class.

class BuyStatsCell: UITableViewCell{

    //these are working fine

    @IBOutlet weak var category: UILabel!
    @IBOutlet weak var average: UILabel!
    @IBOutlet weak var price: UILabel!


    //Outlet for Label and Stepper - How do I make these work?

    @IBOutlet weak var purchaseAmount: UILabel!
    @IBOutlet weak var addSubtract: UIStepper!

    //Action for Stepper - And this?

    @IBAction func stepperAction(_ sender: UIStepper) {
        self.purchaseAmount.text = Int(sender.value).description

    }

}

And I understand the concept of reusing the cell in the cellForRowAt indexPath

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "BuyStatsTabCell", for: indexPath) as! BuyStatsCell

        cell.isUserInteractionEnabled = false

 //these are working 

        cell.category.text = categories[indexPath.row]
        cell.price.text = String(prices[indexPath.row])
        cell.average.text = String(averages[indexPath.row])

//but is there something I need to add here to keep the correct Stepper and Label for each class?

    return cell
}

One of the already asked questions includes a protocol and another function in the ViewController like this

protocol ReviewCellDelegate{
    func stepperButton(sender: ReviewTableViewCell)
}

func stepperButton(sender: ReviewTableViewCell) {
    if let indexPath = tableView.indexPathForCell(sender){
        print(indexPath)
    }
}

I don't know if this is the approach I should be trying to take. I am looking for the simplest solution, but I am having trouble putting the pieces together.

Any help is appreciated. Thanks.


Solution

  • Easiest solution (simplyfied):

    The magic is: When you are tapping the stepper the label as well as the data source array will be updated. So even after scrolling the cell will get always the actual data.

    With this way you don't need protocols or callback closures. It's only important that the model is a class to have reference type semantics.