danielbh
danielbh

Reputation: 197

A UITableCell Background color repeating on other cells when it shouldn't

The following code snippet when applied to a UITableView should only make the first cell orange, but instead makes ever 15th cell orange too. Any idea how to just make the one cell orange? Or is this a bug? I'm using ios8.

class ViewController: UITableViewController {

var links: [Int] = []

override func viewDidLoad() {
    for index in 1...100 {
        links.append(index)
    }

}

@IBOutlet var aTableView: UITableView!

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

override func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {

    if indexPath.row == 0 {
        cell.backgroundColor = UIColor.orangeColor()
    }
}

Upvotes: 0

Views: 385

Answers (2)

A-Live
A-Live

Reputation: 8944

When you dequeueing cells, it means that the cells that are no longer visible are returned at

var cell = self.aTableView?.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as Cell

One of them is changed to have an orange background, if you scroll back to the top of the table it will likely produce another orange cell. You need to keep it in mind when setting up the cells appearance and always reset to default values if there's no special value.

Upvotes: 0

Daniel Brim
Daniel Brim

Reputation: 507

It's not a bug, it's a feature! (But really though).

You see, those cells get reused. If you want cell 0 to be orange, you have to make sure the other cells are their regular color.

Like so:

if indexPath.row == 0 {
  cell.backgroundColor = UIColor.orangeColor()
} else {
  cell.backgroundColor = UIColor.whiteColor()
}

Upvotes: 3

Related Questions