ios - 为 iOS 应用程序中的所有 UITableViewCells 设置背景颜色

标签 ios uitableview background-color

在 iOS 应用程序中设置所有 UITableViewCellbackgroundColor 的最简单方法是什么?

考虑一个具有相对大量 UITableViewController 子类的应用程序。背景颜色是通过网络服务指定的。所以在每个 tableViewController 中使用颜色可能不是最简单的事情。

也许每个 tableViewCell 都可以继承一个 UITableViewCell 子类,其中为所有派生类设置了颜色?可能有更简单的方法。

最佳答案

我的建议是单例。例如:

@interface ColorThemeSingleton : NSObject
@property (strong, atomic) UIColor *tableViewBackgroundColor;
+(ColorThemeSingleton *)sharedInstance;
@end

.m:

#import "ColorThemeSingleton.h"
@implementation ColorThemeSingleton
@synthesize tableViewBackgroundColor = _tableViewBackgroundColor;
+(ColorThemeSingleton *)sharedInstance{
    static ColorThemeSingleton *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[ColorThemeSingleton alloc] init];
    });
    return shared;
}
-(id)init{
    if ((self = [super init])){
        _tableViewBackgroundColor = [UIColor whiteColor]; // Default color
    }
    return self;
}
@end

然后在 tableView:cellForRowAtIndexPath: 中的 if(cell==nil){} 之后添加:

cell.backgroundColor = [ColorThemeSingleton sharedInstance].tableViewBackgroundColor;

当您从网络加载颜色时,将属性的值设置为获取的颜色。下一次单元格通过 tableView:cellForRowAtIndexPath: 时,颜色将是新颜色。

所以基本上只需将 #import""cell.backgroundColor = 添加到 tableViewdataSource。对我来说,这比更改每个 Controller 上的 UITableViewCell 类要好得多。

关于ios - 为 iOS 应用程序中的所有 UITableViewCells 设置背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8997288/

相关文章:

iOS 6 和 iOS 7 UIButton 标签垂直对齐

ios - MKAnnotationView:内存泄漏

ios - 在 Realm 中删除一对多关系的项目

ios - 试图从 UITableView 返回选定的单元格,但它只返回 nil

css - 背景色和背景色有什么区别

ios - `UITabBarController` 切换标签时去除黑色背景

ios - 如何在其中的内容(文本)数量之后缩放 UITableViewCell?

ios - UITapGesture 删除了在放弃键盘响应程序时从 UITableView 中进行选择的功能

html - 如何使 div 组的背景颜色更宽?

iOS:UITableViewCell 的默认背景颜色是什么