美文网首页
iOS UITableViewCell点击效果下, 子控件背景

iOS UITableViewCell点击效果下, 子控件背景

作者: 何以_aaa | 来源:发表于2017-08-11 15:23 被阅读187次

1.问题:

UITableViewCell在有选中效果时,选中状态下, cell的子控件也会被渲染, 从而改变背景色。

2.解决方案:

自定义cell,继承UITableViewCell,重写下面2个方法

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated

2.1修改个别子控件背景色,注意一定调用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的调用位置没有影响
setHighlighted 方法super的调用位置测试必须在此位置

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    // 调用super
    [super setSelected:selected animated:animated];

    // 获取 contentView 所有子控件
    NSArray<__kindof UIView *> *subViews = self.contentView.subviews;
    // 创建颜色数组
    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;
    // 创建颜色数组
    NSMutableArray *colors = [NSMutableArray array];

    for (UIView *view in subViews) {
        // 获取所有子控件颜色
        [colors addObject:view.backgroundColor ?: [UIColor clearColor]];
    }
    // 调用super
    [super setHighlighted:highlighted animated:animated];

    // 修改控件颜色
    for (int i = 0; i < subViews.count; i++) {
        subViews[i].backgroundColor = colors[i];
    }
}```

相关文章

网友评论

      本文标题: iOS UITableViewCell点击效果下, 子控件背景

      本文链接:https://www.haomeiwen.com/subject/byalrxtx.html