Swift - Increment Label with Stepper in TableView Cell

為{幸葍}努か 提交于 2019-11-27 14:14:53

Easiest solution (simplyfied):

  • Create a model BuyStat with a property purchaseAmount (it's crucial to be a class).
    You are strongly discouraged from using multiple arrays as data source

    class BuyStat {
    
        var purchaseAmount = 0.0
    
        init(purchaseAmount : Double) {
            self.purchaseAmount = purchaseAmount
        }
    }
    
  • In the view controller create a data source array

    var stats = [BuyStat]()
    
  • In viewDidLoad create a few instances and reload the table view

    stats = [BuyStat(purchaseAmount: 12.0), BuyStat(purchaseAmount: 20.0)]
    tableView.reloadData()
    
  • In the custom cell create a property buyStat to hold the current data source item with an observer to update stepper and label when buyStat is set

    class BuyStatsCell: UITableViewCell {
    
        @IBOutlet weak var purchaseAmount: UILabel!
        @IBOutlet weak var addSubtract: UIStepper!
    
        var buyStat : BuyStat! {
            didSet {
                addSubtract.value = buyStat.purchaseAmount
                purchaseAmount.text = String(buyStat.purchaseAmount)
            }
        }
    
        @IBAction func stepperAction(_ sender: UIStepper) {
            buyStat.purchaseAmount = sender.value
            self.purchaseAmount.text = String(sender.value)
        }
    }
    
  • In cellForRowAtIndexPath get the data source item and pass it to the cell

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BuyStatsTabCell", for: indexPath) as! BuyStatsCell
        cell.buyStat = stats[indexPath.row]
        return cell
    }
    

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!