iphone - 无法在 UITableViewCell 中设置自定义背景颜色

标签 iphone ios objective-c cocoa-touch uitableview

我正在使用此代码自定义单元格背景 View 的颜色:

UIColor *cellBackgroundColor = [UIColor colorWithRed:255.0 green:255.0 blue:255.0 alpha:1.0];
cell.contentView.backgroundColor = cellBackgroundColor;

问题是,它不起作用。这段代码虽然工作得很好:

cell.contentView.backgroundColor = [UIColor redColor];

这里有什么问题?我不能根据自己的喜好自定义单元格的颜色吗?还是我做错了什么?

最佳答案

你必须用这个 Delegate 设置 Cell Background:-

- (void)tableView: (UITableView*)tableView
  willDisplayCell: (UITableViewCell*)cell
forRowAtIndexPath: (NSIndexPath*)indexPath
{

   // UIImage *img = [UIImage imageNamed:@"button.png"];  // get your background image

    UIColor *cellBackgroundColor = [UIColor colorWithRed:255/255.0 green:108/255.0 blue:61/255.0 alpha:1.0]; //if you want to set color then use this line

  //  UIColor *backgroundColor = [[UIColor alloc] initWithPatternImage: img];
    cell.backgroundColor = cellBackgroundColor;
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.detailTextLabel.backgroundColor = [UIColor clearColor];
}

你的 table 看起来像:-

enter image description here

Taking an RGB color and normalizing it with UIColor on the iPhone

Your values are between 0 and 255. Use them to create a UIColor:

    float r; float g; float b; float a;

    [UIColor colorWithRed:r/255.f
                    green:g/255.f
                     blue:b/255.f    
                    alpha:a/255.f];

关于iphone - 无法在 UITableViewCell 中设置自定义背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14454406/

相关文章:

ios - 如何打开/关闭 iPhone 相机闪光灯?

ios - CollectionView 在滚动时突出显示不正确的单元格

ios - 如何将NSArray保存到文件并从文件中检索NSArray

iOS 8.2 [NSUserDefaults standardUserDefaults] 返回 nil

ios - 如何在 IOS 中滚动表格 View 时隐藏导航栏和标签栏

ios - 如何在自定义 Xcode 项目模板中创建或定义新目标

iphone - Xcode 4 不调整文字大小

iphone - UINavigationController 栈

ios - 应用关闭时UILocalNotification是否被取消?

ios - 在重叠区域点击手势事件