EBF
EBF

Reputation: 1

Repeating values in Stepper inside TableViewCell when scrolling

Stepper problem when cells need scroll.

My_TableViewCell.swift

import UIKit

class My_TableViewCell: UITableViewCell {

@IBOutlet weak var My_Label1: UILabel!
@IBOutlet weak var My_Label2: UILabel!
@IBOutlet weak var My_Stepper: UIStepper!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

...    

My_TableViewController.swift

import UIKit

var My_Ids = ["C01","C02","C03","C04","C05","C06","C07","C08","C09","C10"]
var My_Values = ["0","0","0","0","0","0","0","0","0","0"]

class My_TableViewController: UITableViewController {

@IBAction func My_Stepper(sender: AnyObject) {

    let point = sender.convertPoint(CGPointZero, toView: tableView)
    let indexPath = self.tableView.indexPathForRowAtPoint(point)!
    let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! My_TableViewCell
    cell.My_Label2.text = "\(Int(cell.My_Stepper.value))"

}

...

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return My_Ids.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell =
    self.tableView.dequeueReusableCellWithIdentifier(
        "My_TableCell", forIndexPath: indexPath)
        as! My_TableViewCell

    let row = indexPath.row
    cell.My_Label1.text = My_Ids[row]
    cell.My_Label2.text = "\(Int(cell.My_Stepper.value))"
    return cell
}

...

When all cells fit in a "page" the Stepper works well but if the cells are resized and you need scroll the tableview the values are repeated in other cells.

If you alter the value on the cells C06 and C07 this will to reflect C01 and C02 cells and vice-versa.

Please view this image showing the snapshots with the errors

Upvotes: 0

Views: 370

Answers (1)

iAJ
iAJ

Reputation: 11

UITableViewController intentionally reuses cells as an optimization. You need to clear the old cell settings as part of your solution. Add a prepareForReuse method to your My_TableViewCell class. You do this:

- (void) prepareForReuse
{
    [super prepareForReuse];
    // clear previous cell settings
}

Additional Notes:

  • recommend against calling cellForRowAtIndexPath directly. See this thread.
  • recommend you use Pascal casing for class names: Use MyTableViewCell instead of My_TableViewCell.

Upvotes: 1

Related Questions