在 iOS 应用程序中设置所有 UITableViewCell
的 backgroundColor
的最简单方法是什么?
考虑一个具有相对大量 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 =
添加到 tableView
的 dataSource
。对我来说,这比更改每个 Controller 上的 UITableViewCell
类要好得多。
关于ios - 为 iOS 应用程序中的所有 UITableViewCells 设置背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8997288/