Cell.backgroundColor does not respond if specified in the View table: cellForRowAtIndexPath

I am trying to color a specific row of a table in red, so I tried adding

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ... init Code here cell.backgroundColor = [UIColor redColor]; cell.accessoryType = UITableViewCellAccessoryCheckmark; } 

An auxiliary flag will appear, but not red.

Later I discovered that by putting it in tableView: willDisplayCell, it works. Is it for design? why does it ignore the value that I already set at the time the cell was initialized?

+6
source share
2 answers

The appearance of the cell is configured in tableView:willDisplayCell . So, to answer your question, yes, it is by design. Accessory aspects and cell contentView subparagraphs must be changed / assigned in cellForRowAtIndexPath .

From the documentation for tableView:willDisplayCell:forRowAtIndexPath: ::

The table view sends this message to its delegate just before it uses the cell to draw a row, thereby allowing the delegate to customize the cell object before it is displayed. This method gives the delegate the opportunity to override the state properties that were previously set in table form, such as selection and background color. After the delegate returns, only the alpha and frame properties are set in the table view, and then only when the lines are animated when they enter or exit.

+3
source

FYI, Ravi's answer is correct, but if you want to simplify your implementation, you can also set the background color of the cellView to achieve the same effect.

cell.contentView.backgroundColor = [UIColor redColor];

This is not a 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; } 
+1
source

Source: https://habr.com/ru/post/905781/


All Articles