当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS: UITableViewCell点击效果下, 防止子控件背景颜色改变

iOS: UITableViewCell点击效果下, 防止子控件背景颜色改变

2018年09月14日  | 移动技术网移动技术  | 我要评论
uitableviewcell在选中状态下, 上面的子控件会被渲染, 而改变颜色。

如下图所示:

\
效果
橙色按钮被渲染, 颜色改变

有时, 我们不想要子控件的颜色被渲染, 而是在整个点击过程中颜色都不变

如下图所示:

\
目标效果

我们可以在自定义的cell中(继承自uitableviewcell)重写下面两个方法:

- (void)setselected:(bool)selected animated:(bool)animated
- (void)setselected:(bool)selected animated:(bool)animated

具体实现如下

- (void)setselected:(bool)selected 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 setselected:selected animated:animated];
    // 修改控件颜色
    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];
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网