两个UITableView Cell颜色更改

时间:2013-12-29 05:41:15

标签: ios objective-c uitableview

我希望每两个细胞具有相同的背景颜色 所以单元格1和2是Color_FIRST 单元格3和4是Color_Second 单元格5和6是COLOR_first 等等.. 所以最后我试图翻转COLOR_CURRENT,但代码似乎不起作用;

.h file

extern UIColor *   COLOR_FIRST;
extern UIColor *   COLOR_SECOND;
extern UIColor *   COLOR_CURRENT;

.m file

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIColor*  COLOR_FIRST = [[UIColor alloc] initWithRed:21.0f/255 green:180.0f/255  blue:1   alpha:1];
     UIColor*  COLOR_SECOND = [[UIColor alloc] initWithRed:0/255.f green:255/255.f  blue:0 alpha:1];
     UIColor*  COLOR_CURRENT = COLOR_SECOND;
     cell.contentView.backgroundColor = COLOR_CURRENT;
     if ( indexPath.row % 2) {
//flip COLOR_CURRENT if in EVEN cell
         if (COLOR_CURRENT == COLOR_FIRST) {
             UIColor*  COLOR_CURRENT = COLOR_SECOND;
         }else{
             UIColor*  COLOR_CURRENT = COLOR_FIRST;
         }
     }
     return cell;
  }

谢谢大家;

2 个答案:

答案 0 :(得分:1)

试试这个

if (indexPath.row % 4 == 0 || indexPath.row % 4 == 1) {
    cell.contentView.backgroundColor = COLOR_FIRST;
} else {
    cell.contentView.backgroundColor = COLOR_SECOND;
}

答案 1 :(得分:0)

保持您的表格视图委托尽可能轻薄。

您可以创建UITableViewCell扩展程序。

的UITableViewCell + Color.h

@interface UITableViewCell(Color)

-(void)setColorForIndexPath:(NSIndexPath*)indexPath;

@end

的UITableViewCell + Color.m

@implementation UITableViewCell(Color)

-(void)setColorForIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.row % 4 == 0 || indexPath.row % 4 == 1) {
        self.contentView.backgroundColor = COLOR_FIRST;
    } else {
        self.contentView.backgroundColor = COLOR_SECOND;
    }
}

@end

然后:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    /* DEQUEUE CELL HERE */

    [cell setColorForIndexPath:indexPath];

    return cell;

}