Set background color of UITableViewCell

前端 未结 6 1298
执念已碎
执念已碎 2021-02-15 22:47

I have looked around to find a solution for setting the background color of the accessoryView to the same background color as the cell´s contentView.

    cell.co         


        
6条回答
  •  北海茫月
    2021-02-15 23:17

    - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
        cell.backgroundColor = [UIColor greenColor];
    }
    

    Using this UITableViewDelegate method, you can set the color of cells to different colors. Note that Apple explicitly advise you to make changes to the backgroundColor property within the tableView:willDisplayCell:ForRowAtIndexPath: method in the docs, which state:

    If you want to change the background color of a cell, do so in the tableView:willDisplayCell:forRowAtIndexPath: method of your table view delegate

    Indeed, in iOS 6, changes to the property from anywhere else (like the tableView:cellForRowAtIndexPath: method) would have no effect at all. That no longer seems to be the case in iOS 7, but Apple's advice to modify the property from within tableView:willDisplayCell:ForRowAtIndexPath: remains (without any explanation).

    For alternating colors, do something like this example:

    - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
        if (indexPath.row % 2) {
            cell.backgroundColor = [UIColor yellowColor];
        } else {
            cell.backgroundColor = [UIColor redColor];    
        }
    }
    

提交回复
热议问题