0

Im new to IOS development, and now I have issues in cell.textLabel.textColor

what I did is implementing a tableview, and set color according to the section, as I show below, I have 4 section each has 7 rows. enter image description here As you can see I only set text color to red when this label is in 0 section,However, the result is:

enter image description here

the color is wrong for rest of the sections, as you can see ,some of them become red.

but if I uncommented the code in the else scope, set the color to black, it worked.

enter image description here enter image description here

Qing
  • 1,401
  • 2
  • 21
  • 41
  • So there is no question? The behavior is caused because UITableView reuses its cells. If you don't clear such attributes in `prepareForReuse()` in the cell subclass you have to set the attribute in all branches of your `tableView:cellForRowAtIndexPath:` method – Matthias Bauch Apr 04 '15 at 10:31
  • so the UITableView reuse the cell, and there's no certain rules for the color reusage? since the color is totally in a mess – Qing Apr 04 '15 at 11:55

2 Answers2

1

That is the expected behavior.

UITableView reuses the cells that have the same identifier. So, if you only set them to red in section 0, they will eventually be reused, and since you never told what the reusable state is, they will reuse the red color state.

You can solve this the way you did (providing a default state when the section is different than zero), or you can implement the method -(void)prepareForReuse in your custom cell (that extends UITableViewCell).

Tiago Almeida
  • 14,081
  • 3
  • 67
  • 82
  • then is there any rules for the cell re-usage? since the color in the screen is totally in a mess without any pattern – Qing Apr 04 '15 at 11:57
  • It depends on the way you want to organize your code base. I usually do this kind of stuff in prepareForReuse, since it is a "default" color. I leave the defaults in the prepareForReuse. But it can be easier to have a "setup" for your cell inside your cell and simply define the standard there. It all depends on your situation :) – Tiago Almeida Apr 04 '15 at 12:23
1

This is the expected behavior as the other guys said. You should have both textColor=black and textColor=red because your UITableViewController is considering all cells with Identifier "Cell" the same thing. If you are going to make a lot of customization on the cell I would suggest to create a new custom cell with different identifier so your UITableViewController will be able to differentiate it

Dharmesh Dhorajiya
  • 3,976
  • 9
  • 30
  • 39
BlackM
  • 3,927
  • 8
  • 39
  • 69