30

每当我将附件视图添加到我的 UITableViewCell 时,它不会携带背景颜色?我将 UISwitch 设置为我的附件视图,并且我在 cell.backgroundColor 属性中设置的颜色仅影响 contentView 而不是附件视图。我已经尝试了一切将它们设置为相同的值。我尝试将 cell.backgroundView.backgroundColor 和 cell.accessoryView.backgroundColor 属性设置为我想要的颜色,但没有任何效果。我还尝试在 contentView 中创建一个子视图,它解决了 backgroundColor 问题(通过避免它),但它产生了问题,当文本太长时,开关位于 cell.textLabel 的顶部。

有没有办法我可以修改accessoryView的背景颜色而不在contentView中创建子视图,或者改变cell.textLabel的长度而不继承UITableViewCell?

4

5 回答 5

69

在阅读文档(一个新颖的想法)后,我找到了文章“ A Closer Look at Table-View Cells ”。它帮助我了解了细胞的组成,我找到了答案……

细胞看起来像这样...

替代文字

因为 cell.accessoryView 是 cell.contentView 的姊妹视图,所以我不得不向 cell.contentView 询问它的超级视图,然后我能够一次更改两个视图的背景颜色。这是代码的样子......

// Cell Formatting
cell.contentView.superview.backgroundColor = [UIColor greenColor];

我知道这很简单,但我是新手,我花了很长时间才放慢速度阅读文档。希望这可以帮助其他一些人!

于 2010-08-14T18:20:47.283 回答
46
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor yellowColor];
}
于 2011-05-07T14:49:59.777 回答
15
 UIView *myView = [[UIView alloc] initWithFrame:cell.frame];
 myView.backgroundColor = [UIColor colorWithRed:214.00/255.00 green:233.00/255.00 blue:247.00/255.00 alpha:1.0];
 cell.backgroundView = myView;
 [myView release];
于 2011-09-30T06:26:16.110 回答
3

如果您想将辅助视图背景颜色与单元格的背景颜色混合,在 iOS8 和 Swift 中,这就像 tableView(_, cellForRowAtIndexPath:) 方法中的魅力:

let color = cell.contentView.backgroundColor
cell.backgroundColor = color
于 2015-03-27T04:06:37.733 回答
1

@Zak,首先感谢您提醒我注意单元格布局的细节。很有帮助!
我只想指出以下代码:

self.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"cell_background.png"]];

为我工作。结果是一个背景图像延伸到整个细胞。AccessoryTypeView没有覆盖它!重要的部分是将此代码放入自定义单元格类的layoutSubviews方法中,而不是放入TableViewController 类中的cellForRowAtIndexPath中。在我的例子中,我定义了一个 CustomCell 类,并在其中定义了标签、图像视图等。

注意:以下代码不起作用:

cell.contentView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"cell_background.png"]];

当放入tableView:(UITableView *)tableView cellForRowAtIndexPat方法时。它给了我覆盖单元格的背景,但 AccessoryTypeView 在它上面......

于 2011-03-04T13:19:02.927 回答