[英]Change the selected cell background colour using UIAppearance
I need to change the selected cell background colour for all the cells in my app. 我需要为我的应用程序中的所有单元格更改选定的单元格背景颜色。 As I know there is a way to use
UIAppearance
protocol for this purposes. 据我所知,有一种方法可以为此目的使用
UIAppearance
协议。 Is it possible to realize this by the category for UITableViewCell
? 是否可以通过
UITableViewCell
的类别来实现这一点?
Using appearance proxy you can colour all cells. 使用外观代理,您可以为所有单元着色。 Don't know if you can target specific category.
不知道您是否可以定位特定类别。
To do the colouring put following code in your AppDelegate.m file: 要进行着色,请在AppDelegate.m文件中添加以下代码:
Put [self customCellBackground];
放
[self customCellBackground];
in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions
在
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions
and somewhere at the end: 在结尾处:
- (void)customCellBackground {
UIView *cellBackgroundView =[[UIView alloc] init];
cellBackgroundView.backgroundColor = [UIColor blackColor];
[[UITableViewCell appearance] setSelectedBackgroundView:cellBackgroundView];}
As null 's answer is not for selected cell backgrounds and Armands L. 's answer did not work consistently for me (selecting cells by 'user-tap' did work, but programmatical cell selection showed strange results (like sometimes the selected background was not visible, or did not fill the cell's height properly...). 因为null的答案不适用于选定的单元格背景,而Armands L.的答案不适用于我(通过“用户点击”选择单元格确实有效,但是程序化的单元格选择显示出奇怪的结果(例如有时选定的背景是不可见,或没有正确填充单元格的高度...)。
I found a custom solution that worked: 我找到了一个可行的自定义解决方案:
UITableViewCell
UITableViewCell
self.selectedBackgroundView
in init
and init
初始化self.selectedBackgroundView
并 UIColor
property with UI_APPEARANCE_SELECTOR
for custom selected background color UI_APPEARANCE_SELECTOR
添加自定义UIColor
属性,以自定义选定的背景色 .h
file: .h
文件:
@property (nonatomic) UIColor* selectedCellBackgroundColor UI_APPEARANCE_SELECTOR;
.m
file: .m
文件:
in init
method(s): 在
init
方法中:
self.selectedBackgroundView = [[UIView alloc] init];
and last but not least the setter function for the color: 最后但并非最不重要的是颜色的setter函数:
- (void) setSelectedCellBackgroundColor:(UIColor*) color {
_selectedCellBackgroundColor = color;
self.selectedBackgroundView.backgroundColor = color;
}
You can't do this direct to UITableViewCell, but you can do it for its contentView
: 您不能直接对UITableViewCell执行此操作,但是可以对其
contentView
执行此操作:
[[UIView appearanceWhenContainedIn:[UITableViewCell class], nil] setBackgroundColor:[UIColor redColor]];
Note that it will change all the subViews bg color. 请注意,它将更改所有subViews的bg颜色。
Another option is writing a category or subclass the UITableViewCell
with UI_APPEARANCE_SELECTOR
mark, check this question: 另一个选择是编写带有
UI_APPEARANCE_SELECTOR
标记的UITableViewCell
的类别或子类,请检查以下问题:
iOS: Using UIAppearance to define custom UITableViewCell color iOS:使用UIAppearance定义自定义UITableViewCell颜色
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.