0

How can I increment a value for a specific cell?

I saw this and this post. The prior I couldn't get to work (and is "brittle"?), and the former caused a segmentation fault with the functions incrementHandler() and decrementHandler().

class cell : UITableViewCell {
     @IBOutlet weak var counter: UILabel
     @IBAction func add (sender: AnyButton) {
          counter.text = String(Int(counter.text) + 1) 
          // find it's corresponding stat value (from other class) and update it
          stats[indexPath].counter = Int(counter.text)
     }
}


class tableView: UITableViewController {
    var stats = [Stat]()
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! ExpandedControllerCell
        let stat = stats[indexPath.row]
        cell.titleLabel.text = stat.name
        cell.bigCounterLabel.text = String(stat.counter)
        cell.smallCounterLabel.text = String(stat.counter)
        return cell
    }
}
Community
  • 1
  • 1
user5812721
  • 293
  • 2
  • 13

1 Answers1

1

In your cellForRowAtIndexPath, set a tag on the button. Then, in your IBAction method, use the tag to figure out which cell's button was tapped. Increment a value in an array, and then tell the cell at that indexPath to reload itself. (In cellForRowAtINdexPath, install the counter value into the cell.)

You can also write your button action so it uses the button's frame.origin to ask the table view which cell the button belongs to. That's better and less fragile.

See my answer in this thread for an explanation of how to do that.

Duncan C
  • 128,072
  • 22
  • 173
  • 272