iOS:使用UIAppearance定义自定义的UITableViewCell颜色

如果我在分组的UITableViewCell上设置了backgroundColor属性,背景色成功更改。 大。

但是我想用UIAppearance来改变我所有的UITableViewCells的背景颜色,所以我可以在一个地方做到这一点,并在任何地方影响到一个变化。 这是我的代码:

[[UITableViewCell appearance] setBackgroundColor:[UIColor colorWithRed:30.0/255.0 green:30.0/255.0 blue:30.0/255.0 alpha:1.0]]; 

UITableViewCell实现UIAppearance和UIAppearanceContainer,所以我会认为这将工作。 但事实并非如此。 我也试过使用-[UITableViewCell appearanceWhenContainedIn:(Class)] ,这也不起作用。

有任何想法吗?

更新(2013/7/8) – 已在更新版本的iOS中修复。 不过,如果您的目标是iOS 6或更低版本,则需要了解一下。

你可以责怪苹果这个,而且其实很不错。 从技术上讲backgroundColor 不是通过外观代理来定制的

从苹果的文档:

为了支持外观定制,一个类必须符合UIAppearanceContainer协议,相关的访问器方法必须用UI_APPEARANCE_SELECTOR标记。

如果我们进入像UIBarButtonItem类,并看看tintColor属性,我们看到这个:

 @property(nonatomic,retain) UIColor *tintColor UI_APPEARANCE_SELECTOR; 

所以,因为它标有UI_APPEARANCE_SELECTOR标签,我们知道它与UIAppearance一起UIAppearance

这里的苹果是特别的意思:在UIViewbackgroundColor 没有外观select器标签,但仍与UIAppearance 。 据苹果提供的所有文件不应该,但它呢!

这给人以误导的印象,它将适用于UIView所有子类,包括UITableView 。 这是以前的答案

所以底线是backgroundColor不应该与UIAppearance一起UIAppearance ,但由于某种原因它在UIView 。 不保证在UIView子类上工作,而且在UITableView上完全不起作用。 对不起,我不能给你一个更积极的答案!

您可以创build自己的符合UIAppearance的UITableViewCell的子类,并使用UI_APPEARANCE_SELECTOR标记自定义设置器。 然后在自定义setter的超类上设置单元格backgroundColor。

在你的appDelegate

 [[CustomCell appearance] setBackgroundCellColor:[UIColor redColor]]; 

在你的UItableView子类中

 @interface CustomCell : UITableViewCell <UIAppearance> @property (nonatomic, weak) UIColor *backgroundCellColor UI_APPEARANCE_SELECTOR; 

 @implementation CustomCell @synthesize backgroundCellColor; -(void)setBackgroundCellColor:(UIColor *)backgroundColor { [super setBackgroundColor:backgroundColor]; } 

我在这个例子中使用ARC。

没有子类化 在子类上做这可能不是最好的做法,尤其是如果你想打所有的tableView背景。 这是很多的子类。 很多潜在的错误。 真是一团糟 最好的办法是使用一个类别。 你将不得不为tableViewCell和tableView设置一个。 我将只是展示一个单元格。 tableView上的属性必须是backgroundColor属性。 NB。 我正在将我的方法预先加上“sat”。

// 。H

  #import <UIKit/UIKit.h> @interface UITableViewCell (Appearance)<UIAppearance> @property (strong, nonatomic) UIColor *satBackgroundColor UI_APPEARANCE_SELECTOR; @end 

// .m

 #import "UITableViewCell+Appearance.h" @implementation UITableViewCell (Appearance) - (UIColor *)satBackgroundColor { return self.backgroundColor; } - (void)setSatBackgroundColor:(UIColor *)satBackgroundColor { self.backgroundColor = satBackgroundColor; } @end 

现在在你的appDelegate或者一些经理类中,你将会导入这个类,并且像调用一个外观代理一样调用它。

 UITableViewCell *cell = [UITableViewCell appearance]; cell.satBackgroundColor = [UIColor orangeColor]; 

好吧,现在只要做一个tableView的背景属性。 简单。

我用这个分类。 下面是示例代码在你的.h文件中写入

 *@interface UITableViewCell (MyCustomCell) @property (nonatomic, weak) UIColor *backgroundCellColor UI_APPEARANCE_SELECTOR; @end* 

在你的.m文件中写入

 *@dynamic backgroundCellColor; -(void)setBackgroundCellColor:(UIColor *)backgroundColor { [super setBackgroundColor:backgroundColor]; }* 

它为我工作得很好。 :)谢谢Nate!