Change the selected cell background colour using UIAppearance

余生颓废 提交于 2019-12-18 07:14:23

问题


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. Is it possible to realize this by the category for UITableViewCell?


回答1:


You can't do this direct to UITableViewCell, but you can do it for its contentView:

[[UIView appearanceWhenContainedIn:[UITableViewCell class], nil] setBackgroundColor:[UIColor redColor]];

Note that it will change all the subViews bg color.

Another option is writing a category or subclass the UITableViewCell with UI_APPEARANCE_SELECTOR mark, check this question:

iOS: Using UIAppearance to define custom UITableViewCell color




回答2:


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:

Put [self customCellBackground]; in - (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];}



回答3:


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...).

I found a custom solution that worked:

  1. Subclass UITableViewCell
  2. Initialize self.selectedBackgroundView in init and
  3. Add custom UIColor property with UI_APPEARANCE_SELECTOR for custom selected background color

.h file:

@property (nonatomic) UIColor* selectedCellBackgroundColor UI_APPEARANCE_SELECTOR;

.m file:

in init method(s):

self.selectedBackgroundView = [[UIView alloc] init];

and last but not least the setter function for the color:

- (void) setSelectedCellBackgroundColor:(UIColor*) color {
    _selectedCellBackgroundColor = color;
    self.selectedBackgroundView.backgroundColor = color;
}


来源:https://stackoverflow.com/questions/22476819/change-the-selected-cell-background-colour-using-uiappearance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!