改变UITableView编辑状态的选中背景颜色.

下面先来一个默认的UITableViewCell的选中样式:
这里写图片描述

在不需要有选中状态(无tableView的Edit编辑状态需要选中某个组的时候)*以直接设置UITableViewCell的selectionStyle为None就OK.但是在edit状态的时候selectionStyle如果是None的话.那么将无法选中

这里写图片描述

选中的话又只有那么几种颜色状态可供选择.
那么,如何去修改这个颜色状态呢.

通过Xcode自带的Reveal我们可以偷偷看看层级关系

这是我选中的一个Cell
这里写图片描述

这是这个选中Cell有颜色的背景对应的View
这里写图片描述

我们可以看到这个背景View是

    UITableViewCellSelectedBackground

类型的

在Cell的.m中我们也找到了如下的属性

// Default is nil for cells in UITableViewStylePlain, and non-nil for UITableViewStyleGrouped. The 'selectedBackgroundView' will be added as a subview directly above the backgroundView if not nil, or behind all other views. It is added as a subview only when the cell is selected. Calling -setSelected:animated: will cause the 'selectedBackgroundView' to animate in and out with an alpha fade.
@property (nonatomic, strong, nullable) UIView *selectedBackgroundView;

我们直接设置这个View的backgroundColor属性是没有任何效果的.po出来的属性如下所示
这里写图片描述

既然这个selectedBackgroundView是一个UIView对象.那么我们可以直接替换掉系统给出的默认的View.

大家应该都知道在- (void)layoutSubviews;中我们可以得到当前控件以及子控件的详细属性(主要是frame方面的).那么我们可以在-(void)layoutSubViews中替换掉系统的selectedBackgroundView

- (void)layoutSubviews {
    [super layoutSubviews];
    UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
    selectedBackgroundView.backgroundColor = [UIColor redColor];
    self.selectedBackgroundView = selectedBackgroundView;
}

最后运行时选中的效果是这样的
这里写图片描述

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_18683985/article/details/81665407