objective-c - UITableViewCell背景颜色问题

标签 objective-c cocoa-touch uitableview

我将 UITableViewCell 子类化以将单元格背景颜色设置为我需要的颜色:

.h

@interface DataViewCustomCell : UITableViewCell {
    UIColor* cellColor;
    UIColor* standardColor;
}
- (void) setCellColor: (UIColor*)color;

@end

.m

@implementation DataViewCustomCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void) setCellColor: (UIColor*)color
{
    cellColor = color;
}

- (void) spreadBackgroundColor: (UIView*)that withColor: (UIColor*)bkColor
{
    NSEnumerator *enumerator = [that.subviews objectEnumerator];
    id anObject;

    while (anObject = [enumerator nextObject]) {
        if([anObject isKindOfClass: [UIView class]])
        {
            ((UIView*)anObject).backgroundColor = bkColor;
            [self spreadBackgroundColor:anObject withColor:bkColor];
        }
    }
}

- (void) layoutSubviews {
    [super layoutSubviews]; // layouts the cell as UITableViewCellStyleValue2 would normally look like

    if(!self.selected && NULL != cellColor)
    {
        [self spreadBackgroundColor:self withColor:cellColor];
    }
}

- (void)dealloc
{
    [super dealloc];
}

@end

当我用我想要的颜色调用 setCellColor 时,一切顺利,但是当我没有找到一种方法来设置原始颜色时:当我用 UITableViewStylePlain 样式设置 [UIColor clearColor] 时结果不好看。

Wrong result

如何在不丢失细胞分隔线的情况下获得良好的结果?

最佳答案

我遇到了类似的问题并找到了 edo42 的答案。然而,我当时遇到了一个问题,单元格中文本后面的背景没有显示我设置的背景颜色。我相信这是由于样式:UITableViewCellStyleSubtitle。

如果其他人偶然发现这个问题,我相信在这个问题中找到了更好的解决方案:

UITableViewCellStyleSubtitle 标签的背景颜色? BackgroundColor of UITableViewCellStyleSubtitle labels?

此处转载答案:

要更改表格 View 单元格的背景颜色,您需要在 tableView:willDisplayCell:forRowAtIndexPath: 中设置它,而不是在 tableView:cellForRowAtIndexPath: 中设置它,否则它不会有任何效果,例如:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = [UIColor whiteColor];
}

关于objective-c - UITableViewCell背景颜色问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6346721/

相关文章:

objective-c - 在 UITextField 中换行文本?

objective-c - Xcode/git 不适用于子文件夹

ios - 带有自定义单元格的 UITableView 在 iOS 6 上绘制良好,但在 iOS 7 中完全白色

ios - 为什么 UITableView 呈现额外的行(多于数据数组中的行)?

ios - 当字段来自 sqlite 数据库时点击 didSelectRowAtIndexPath

ios - 如何在 ios 中删除 UIDatePicker 的 setMaximumDate

iOS 将 subview 带回

iPhone : How to display multiple colors in progress bar?

ios - 如何更改 UITableView 中附件 View 的 alpha?

iphone - 在 iOS 上运行无限循环动画