ios交替4种颜色

时间:2015-04-18 02:49:54

标签: ios objective-c

我试图给4个细胞不同的颜色,然后重复它。 (所以不是斑马风格的桌子,但使用4) 为什么这不起作用? 我只有两种颜色......

if (indexPath.row % 4 == 0)
    [cell setColor:[UIColor colorFromHexString:@"35a8e1"]];
if (indexPath.row % 4 == 1)
    [cell setColor:[UIColor colorFromHexString:@"5cb14c"]];
if (indexPath.row % 4 == 2)
    [cell setColor:[UIColor colorFromHexString:@"ec292d"]];
else
    [cell setColor:[UIColor colorFromHexString:@"ee8c1d"]];




+(UIColor*)colorFromHexString:(NSString*)hex
{
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor grayColor];

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

    if ([cString length] != 6) return  [UIColor grayColor];

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];

    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

2 个答案:

答案 0 :(得分:2)

我会实施以下内容,以便更轻松地扣除实际发生的情况:

NSUInteger index = indexPath.row;

if (index % 4 == 0) {
    [cell setColor:[UIColor colorFromHexString:@"35a8e1"]];
} else if (index % 4 == 1) {
    [cell setColor:[UIColor colorFromHexString:@"5cb14c"]];
} else if (index % 4 == 2) {
    [cell setColor:[UIColor colorFromHexString:@"ec292d"]];
} else {
    [cell setColor:[UIColor colorFromHexString:@"ee8c1d"]];
}

以这种方式编写时,您的代码只能执行操作。

另外,我会在第一个if语句上设置一个断点,然后逐步执行整个语句以查看哪个语句正在执行。


或者,使用switch语句可能会使事情更清晰:

 switch (indexPath.row % 4) {
 case 0:
      [cell setColor:[UIColor colorFromHexString:@"35a8e1"]];
      break;
 case 1:
      [cell setColor:[UIColor colorFromHexString:@"5cb14c"]];
      break;
 case 2:
      [cell setColor:[UIColor colorFromHexString:@"ec292d"]];
      break;
 case 3:
      [cell setColor:[UIColor colorFromHexString:@"ee8c1d"]];
      break;
}

答案 1 :(得分:1)

试一试:

if (indexPath.row % 4 == 0)
    [cell setColor:[UIColor colorFromHexString:@"35a8e1"]];
else if (indexPath.row % 4 == 1)
    [cell setColor:[UIColor colorFromHexString:@"5cb14c"]];
else if (indexPath.row % 4 == 2)
    [cell setColor:[UIColor colorFromHexString:@"ec292d"]];
else
    [cell setColor:[UIColor colorFromHexString:@"ee8c1d"]];