Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/95.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 更改UITableViewCell中UILabel的背景色_Ios_Objective C_Cocoa Touch - Fatal编程技术网

Ios 更改UITableViewCell中UILabel的背景色

Ios 更改UITableViewCell中UILabel的背景色,ios,objective-c,cocoa-touch,Ios,Objective C,Cocoa Touch,UITableViewCell是“预构建”的,其中UILabel是初始化后唯一的子视图。我真的很想改变标签的背景色,但无论我做什么,颜色都不会改变。有关守则: UILabel* label = (UILabel*)[cell.contentView.subviews objectAtIndex:0]; label.textColor = [UIColor whiteColor]; label.backgroundColor = [UIColor darkGrayColor]; label.opa

UITableViewCell是“预构建”的,其中UILabel是初始化后唯一的子视图。我真的很想改变标签的背景色,但无论我做什么,颜色都不会改变。有关守则:

UILabel* label = (UILabel*)[cell.contentView.subviews objectAtIndex:0];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor darkGrayColor];
label.opaque = YES;

您的代码片段对我来说很好,但我相信它必须在单元格被添加到表中并显示之后完成。如果从
initWithFrame:reuseIdentifier:
调用,您将得到一个异常,因为尚未创建
UILabel
子视图


最好的解决方案可能是添加您自己的
UILabel
,根据您的标准进行配置,而不是依赖此(非常不稳定的)内置路径。

在分配单元格时,将您自己的标签添加到contentView,而不是依赖于提取内置标签。然后可以控制所有值:

UILabel* label = [[[UILabel alloc] init] autorelease];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor darkGrayColor];
label.opaque = YES;
[cell.contentView addSubview:label];

这不起作用,因为UITableViewCell在layoutSubviews方法中设置其标签背景色

如果要更改内置textLabel或detailTextLabel的颜色,请将UITableViewCell子类化并覆盖LayoutSubView。调用超级实现,然后将backgroundColor属性更改为您想要的

- (void) layoutSubviews
{   
     [super layoutSubviews];

     self.textLabel.backgroundColor = [UIColor redColor];
}

首先,我问这个问题的原因是因为我想依赖摇摇晃晃的路径,即:我不想创建自己的子视图(是的,我就是那么懒)。你说我的代码可以改变背景颜色吗?你能说得更具体一点吗?我也很懒,但这很危险;-)我在调用代码的单元格的init方法中添加了一个延迟调用。它改变了背景颜色(当然还有文本颜色)。这似乎根本不起作用,至少在tableView:CellForRowatineXpath:我试图让事情正常运行的地方没有。有什么提示吗?
for (UIView *views in views.subviews)
{
    UILabel* temp = (UILabel*)[views.subviews objectAtIndex:0];
    temp.textColor = [UIColor whiteColor];        
    temp.shadowColor = [UIColor blackColor];
    temp.shadowOffset = CGSizeMake(0.0f, -1.0f);
}