I am trying to color certain table row with red so I tried adding
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
... init Code here
cell.backgroundColor = [UIColor redColor];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
The accessory Checkmark appears but not the red color.
I later found that by placing it in tableView:willDisplayCell it works. Is this by design? why is it ignoring the value I already set at the moment of initializing the cell?
The look of the cell is customized in tableView:willDisplayCell
. So, to answer your question, yes it is by design. Accessory views and subviews of the contentView
of the cell need to be modified/assigned in cellForRowAtIndexPath
.
From the documentation of tableView:willDisplayCell:forRowAtIndexPath:
:
A table view sends this message to its delegate just before it uses cell to draw a row, thereby permitting the delegate to customize the cell object before it is displayed. This method gives the delegate a chance to override state-based properties set earlier by the table view, such as selection and background color. After the delegate returns, the table view sets only the alpha and frame properties, and then only when animating rows as they slide in or out.
FYI, Ravi's answer is correct, but if you would like to simplify your implementation, you may also set the cell's contentView background color to achieve the same effect.
cell.contentView.backgroundColor = [UIColor redColor];
This is not the documented solution, but the following will work:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
... init Code here
cell.contentView.backgroundColor = [UIColor redColor];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With