我知道我会问一个愚蠢的问题,但请提供一些答案。
如果我有表格 View ,我想设置表格 View 的背景颜色,并且我有一个名为color
的字符串,其值为“gray Color”
。
如何借助字符串color
设置表格 View 的背景颜色。
如需澄清,请回复我。
谢谢。
最佳答案
这里有一些您可以用来入门的代码。我使用了所有 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;
}
关于iphone - 如何设置tableview背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10533570/