iOS15下UICollectionViewCell重写setSelected设置背景色失效问题
iOS15 下 UICollectionViewCell 重写 setSelected 设置背景色不生效解决方案
问题原因
iOS 15 新增了 UIContentConfiguration 内容配置机制,UICollectionViewCell 默认开启 automaticallyUpdatesContentConfiguration 和 automaticallyUpdatesBackgroundConfiguration 两个属性,当cell的选中、高亮等状态发生变更时,系统会自动更新cell的内容和背景配置,直接覆盖开发者手动设置的 backgroundColor 等属性,所以iOS14及更低版本正常的代码在iOS15+上会失效。
解决方案
方案1:关闭系统自动配置(改动最小,兼容原有逻辑)
在 UICollectionViewCell 的初始化方法(initWithFrame: 或 initWithCoder:)中添加以下代码,关闭系统的自动样式覆盖,原有setSelected的逻辑无需修改即可正常运行:
- (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { if (@available(iOS 15.0, *)) { self.automaticallyUpdatesContentConfiguration = NO; self.automaticallyUpdatesBackgroundConfiguration = NO; } // 原有其他初始化逻辑 } return self; }
方案2:适配iOS15+新API(推荐适配新特性)
如果需要适配系统新特性,可以删除原有重写的setSelected逻辑,在cell初始化时注册状态更新回调,所有状态变更的样式调整都在回调内处理:
- (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { if (@available(iOS 15.0, *)) { [self setConfigurationUpdateHandler:^(__kindof UICollectionViewCell * _Nonnull cell) { if (cell.selected) { cell.layer.borderColor = [UIColor colorWithWhite:1 alpha:0.5].CGColor; cell.layer.borderWidth = 2.0f; cell.textLabel.textColor = [UIColor whiteColor]; cell.backgroundColor = kAppDefaultThemeColor; } else { cell.layer.borderColor = kAppDefaultThemeColor.CGColor; cell.layer.borderWidth = 2.0f; cell.textLabel.textColor = [UIColor blackColor]; cell.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5]; } }]; } } return self; } // iOS14及更低版本仍然可以保留原有setSelected逻辑,无需改动 - (void)setSelected:(BOOL)selected { [super setSelected:selected]; if (@available(iOS 15.0, *)) { return; } // 原有逻辑 if (selected) { self.layer.borderColor = [UIColor colorWithWhite:1 alpha:0.5].CGColor; self.layer.borderWidth = 2.0f; self.textLabel.textColor = [UIColor whiteColor]; self.backgroundColor = kAppDefaultThemeColor; } else { self.layer.borderColor = kAppDefaultThemeColor.CGColor; self.layer.borderWidth = 2.0f; self.textLabel.textColor = [UIColor blackColor]; self.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5]; } }
注意:重写
setSelected方法时必须调用父类实现[super setSelected:selected],否则可能导致cell选中状态不同步的问题。
内容的提问来源于stack exchange,提问作者Rahul Vyas
相关产品推荐
相关产品推荐

