这里有一些你可以用来开始的代码。我使用了所有的UIColor's
类颜色来保持代码简洁明了。如果您需要确定其他自定义颜色名称,例如您要求的“灰色颜色”,您将被迫为您要处理的每种颜色编写一个长 if 子句和 if 语句。
- (void)viewDidLoad
{
[super viewDidLoad];
// statically add UIColor class names (for sake of simplicity)
self.colors = [NSArray arrayWithObjects:@"blackColor",
@"darkGrayColor",
@"lightGrayColor",
@"whiteColor",
@"grayColor",
@"redColor",
@"greenColor",
@"blueColor",
@"cyanColor",
@"yellowColor",
@"magentaColor",
@"orangeColor",
@"purpleColor",
@"brownColor",
@"aColor",
@"lightTextColor",
@"darkTextColor",
@"groupTableViewBackgroundColor",
@"viewFlipsideBackgroundColor",
@"scrollViewTexturedBackgroundColor",
@"underPageBackgroundColor",
nil];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSString *colorName = [self.colors objectAtIndex:indexPath.row];
SEL colorSelector = NSSelectorFromString(colorName);
if ([UIColor respondsToSelector:colorSelector])
{
UIColor *cellColor = [UIColor performSelector:colorSelector];
const CGFloat *componentColors = CGColorGetComponents(cellColor.CGColor);
int numComponents = CGColorGetNumberOfComponents(cellColor.CGColor);
// get inverse color for cell text
UIColor *inverseColor = [UIColor whiteColor];
if (numComponents == 4)
{
inverseColor = [[[UIColor alloc] initWithRed:(255 - 255 * componentColors[0])
green:(255 - 255 * componentColors[1])
blue:(255 - 255 * componentColors[2])
alpha:componentColors[3]] autorelease];
} else if (numComponents == 2) {
inverseColor = [[[UIColor alloc] initWithRed:(255 - 255 * componentColors[0])
green:(255 - 255 * componentColors[0])
blue:(255 - 255 * componentColors[0])
alpha:componentColors[1]] autorelease];
}
cell.contentView.backgroundColor = cellColor;
cell.textLabel.textColor = inverseColor;
cell.textLabel.text = colorName;
} else {
cell.contentView.backgroundColor = [UIColor whiteColor];
cell.textLabel.text = [NSString stringWithFormat:@"Unknown color (%@)", colorName];
cell.textLabel.textColor = [UIColor blackColor];
}
cell.textLabel.backgroundColor = cell.contentView.backgroundColor;
return cell;
}