使用UIAppearance更改选定的单元格背景颜色
我需要更改我的应用程序中所有单元格的选定单元格背景颜色。 据我所知,有一种方法可以将UIAppearance
协议用于此目的。 有没有可能通过UITableViewCell
的类别来实现这一点?
你不能直接去UITableViewCell,但你可以为它的contentView
做:
[[UIView appearanceWhenContainedIn:[UITableViewCell class], nil] setBackgroundColor:[UIColor redColor]];
请注意,它会改变所有的子视图颜色。
另一个select是用UI_APPEARANCE_SELECTOR
标记写一个UITableViewCell
的类或子类,检查这个问题:
iOS:使用UIAppearance定义自定义的UITableViewCell颜色
使用外观代理可以为所有单元格着色。 不知道你是否可以针对特定的类别。
在AppDelegate.m文件中将下列代码着色:
把[self customCellBackground];
在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions
并在最后的某个地方:
- (void)customCellBackground { UIView *cellBackgroundView =[[UIView alloc] init]; cellBackgroundView.backgroundColor = [UIColor blackColor]; [[UITableViewCell appearance] setSelectedBackgroundView:cellBackgroundView];}
由于null的答案不适用于选定的单元格背景,而Armands L.的答案对我来说并不一致 (通过'user-tap'select单元格确实有效,但程序性单元格select显示出奇怪的结果(例如有时选定的背景是不可见,或没有正确填充单元格的高度…)。
我find了一个自定义的解决scheme:
- 子类
UITableViewCell
- 在
init
和中初始化self.selectedBackgroundView
- 使用
UI_APPEARANCE_SELECTOR
为自定义选定的背景颜色添加自定义UIColor
属性
.h
文件:
@property (nonatomic) UIColor* selectedCellBackgroundColor UI_APPEARANCE_SELECTOR;
.m
文件:
在init
方法中:
self.selectedBackgroundView = [[UIView alloc] init];
最后但并非最不重要的色彩设置function:
- (void) setSelectedCellBackgroundColor:(UIColor*) color { _selectedCellBackgroundColor = color; self.selectedBackgroundView.backgroundColor = color; }