1.問題:
UITableViewCell在有選中效果時邓梅,選中狀態(tài)下, cell的子控件也會被渲染, 從而改變背景色酱讶。
2.解決方案:
自定義cell,繼承UITableViewCell,重寫下面2個方法
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
2.1修改個別子控件背景色梳杏,注意一定調(diào)用super
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
self.testLabel.backgroundColor = [UIColor orangeColor];
}
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
[super setHighlighted:highlighted animated:animated];
self.testLabel.backgroundColor = [UIColor orangeColor];
}
2.2修改所有子控件背景色
注意:
setSelected 方法super的調(diào)用位置沒有影響
setHighlighted 方法super的調(diào)用位置測試必須在此位置
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
// 調(diào)用super
[super setSelected:selected animated:animated];
// 獲取 contentView 所有子控件
NSArray<__kindof UIView *> *subViews = self.contentView.subviews;
// 創(chuàng)建顏色數(shù)組
NSMutableArray *colors = [NSMutableArray array];
for (UIView *view in subViews) {
// 獲取所有子控件顏色
[colors addObject:view.backgroundColor ?: [UIColor clearColor]];
}
// 修改控件顏色
for (int i = 0; i < subViews.count; i++) {
subViews[i].backgroundColor = colors[i];
}
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
// 獲取 contentView 所有子控件
NSArray<__kindof UIView *> *subViews = self.contentView.subviews;
// 創(chuàng)建顏色數(shù)組
NSMutableArray *colors = [NSMutableArray array];
for (UIView *view in subViews) {
// 獲取所有子控件顏色
[colors addObject:view.backgroundColor ?: [UIColor clearColor]];
}
// 調(diào)用super
[super setHighlighted:highlighted animated:animated];
// 修改控件顏色
for (int i = 0; i < subViews.count; i++) {
subViews[i].backgroundColor = colors[i];
}
}```