简体   繁体   English

在iOS应用中为所有UITableViewCells设置背景颜色

[英]Set background color for all UITableViewCells in iOS app

What's the easiest way to set the backgroundColor of all UITableViewCell s in an iOS app? 在iOS应用中设置所有UITableViewCellbackgroundColor的最简单方法是什么?

Consider an app that has a relatively large number of UITableViewController subclasses. 考虑一个具有大量UITableViewController子类的应用程序。 The background color is specified via a web service. 通过Web服务指定背景色。 So using the color in each tableViewController is probably not the easiest thing to do. 因此,在每个tableViewController中使用颜色可能不是最容易的事情。

Perhaps every tableViewCell could inherit a UITableViewCell subclass where the color is set for all derived classes? 也许每个tableViewCell都可以继承UITableViewCell子类,其中为所有派生类设置颜色? There might be an easier way. 可能有一种更简单的方法。

My recommendation would be a singleton. 我的建议是单身。 for example: 例如:

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

and the .m : .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

Then just after the if(cell==nil){} in tableView:cellForRowAtIndexPath: you would add: 然后在tableView:cellForRowAtIndexPath:if(cell==nil){} ,您将添加:

cell.backgroundColor = [ColorThemeSingleton sharedInstance].tableViewBackgroundColor;

And when you load you color from the web, set the value of the property to the fetched color. 当您从Web加载颜色时,将属性的值设置为获取的颜色。 The next time a cell runs through tableView:cellForRowAtIndexPath: the color will be the new color. 下次单元格通过tableView:cellForRowAtIndexPath:运行时tableView:cellForRowAtIndexPath:颜色将为新颜色。

So basically just add the #import"" and cell.backgroundColor = to the tableView 's dataSource . 因此,基本上只需将#import""cell.backgroundColor =tableViewdataSource To me that's a lot better than changing the UITableViewCell 's class on every controller. 对我来说,这比在每个控制器上更改UITableViewCell的类要好得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM