UITableView cell background color

前端 未结 8 677
别那么骄傲
别那么骄傲 2020-12-08 03:13

how to set different background colors for cells in a UITableView (specifically rainbow color for seven cells)

相关标签:
8条回答
  • 2020-12-08 03:27

    If you want to set cell color based on some state in the actual cell data object, then this is another approach:

    If you add this method to your table view delegate:

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

    Then in your cellForRowAtIndexPath method you can do:

    if (myCellDataObject.hasSomeStateThatMeansItShouldShowAsBlue) {
        cell.contentView.backgroundColor = [UIColor blueColor];
    }
    

    This saves having to retrieve your data objects again in the willDisplayCell method.

    0 讨论(0)
  • 2020-12-08 03:32

    Try this

    cell.backgroundVIew.backgroundColor = [UIColor orangeColor];
    
    0 讨论(0)
  • 2020-12-08 03:36

    Pretty sure UITableViewCell is a subclass of UIView, so:

    cell.backgroundColor = [UIColor blueColor];
    

    For awful rainbow colors, here is an example:

    static NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor yellowColor], etc..., nil];
    cell.backgroundColor = [colors objectAtIndex:indexPath.row];
    
    0 讨论(0)
  • 2020-12-08 03:37

    Do not forget to set background color of your tableView to clearColor. Otherwise the clearColor of cell will not be displayed as the background color of tableView will be whiteColor by default. And even when the cell color turns to clearColor whiteColor will be displayed because the tableView background color is still whiteColor. Remenber.

    0 讨论(0)
  • 2020-12-08 03:38

    If you've subclassed UITableViewCell, you can reliably set self.backgroundColor in -layoutSubviews. At least in my experience, this works in the odd cases where tableView:willDisplayCell:forRowAtIndexPath: does not.

    0 讨论(0)
  • 2020-12-08 03:40

    Set the backgroundColor property:

    cell.backgroundColor = [UIColor redColor];
    

    Note that the backgroundColor must be set in the tableView:willDisplayCell:forRowAtIndexPath: method (from UITableViewCell reference):

    Note: If you want to change the background color of a cell (by setting the background color of a cell via the backgroundColor property declared by UIView) you must do it in the tableView:willDisplayCell:forRowAtIndexPath: method of the delegate and not in tableView:cellForRowAtIndexPath: of the data source. Changes to the background colors of cells in a group-style table view has an effect in iOS 3.0 that is different than previous versions of the operating system. It now affects the area inside the rounded rectangle instead of the area outside of it.

    Use the indexPath parameter to achieve the rainbow effect.

    0 讨论(0)
提交回复
热议问题