开发者

cell.backgroundColor question

开发者 https://www.devze.com 2023-04-02 08:21 出处:网络
I found this handy code on t开发者_开发百科he internet, - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

I found this handy code on t开发者_开发百科he internet,

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
 cell.backgroundColor = (indexPath.row%2)?[UIColor grayColor]:[UIColor clearColor];
 }

I know that it makes every row a gray, then clear, then gray sort of pattern. But I want to switch off between a light gray and a dark gray. How can I modify the above code so I can switch between those two colors?

Thanks!


Both darkGrayColor and lightGrayColor are valid color names, so change it to the code below. All I did was change your color names.

(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = (indexPath.row%2)
        ? [UIColor lightGrayColor]
        : [UIColor darkGrayColor];
}

Explanation of how the alternating row colors work: The indexPath.row % 2 performs a modulus on the index: if it has no remainder when divided by two, the color will be lightGrayColor; otherwise, it will be darkGrayColor. I have spaced out the code a little to make it more obvious what is happening.


There is a good example on how to alternate cells background colors made by apple: It's called AdvancedTableViewCells and is actually the tableview cell used in the App Store.

In the example they are alternating two different Images as backgroundViews of the cells by passing a flag to the cell.

self.backgroundView = [[[UIImageView alloc] initWithImage:backgroundImage] autorelease];

If you have trouble understanding the example let me know...

0

精彩评论

暂无评论...
验证码 换一张
取 消