iOS Tableview,高亮状态下使separatorLine不消失的自定义方案

iOS8之后(8之前未验证)tableview cell 在高亮时,separatorLine 在系统默认下是隐藏的,同时隐藏了上边相邻 cell 的 seperatorLine。这在许多产品需求中是不受欢迎的,所以有必要自定义一下分割线的实现。

首先分析下seperatorLine隐藏的原因:

status = normal 时,cell 层级结构为 UITableViewCellContentView、_UITableViewCellSeparatorView;
status = highlighted 时,层级结构为 UIView、UITableViewCellContentView、_UITableViewCellSeparatorView,UIView实为 cell.selectBackgroundView。

高亮时系统会自动处理控件的颜色值,所以 separatorView 颜色看起来消失了。经测试,不仅CellSeparatorView,contentView 随便加 add 一个控件,高亮时都会呈现selectBackgroundView 的颜色。

那上边相邻 cell seperatorLine 隐藏的原因是什么呢?

我们打印 line description,如下:
<_UITableViewCellSeparatorView: 0x7fe651d61c90; frame = (12 59.5; 296 0.5); >
打印高亮时 selectBackgroundView description:

可以发现 selectBackgroundView 是不等于 cell frame 的,frame 上下各有 0.5 像素的延伸,正好造成了覆盖上边相邻 cell seperatorLine 的效果!如上所述,系统也会对上边相邻 cell 的  separateLine 做出默认处理。

自定义方案的思路:

1、设置 UITableViewCellSeparatorStyleNone。

2、为了不覆盖相邻 cell 的 separateLine,设置 selectBackgroundView.layer.clipToBounds = YES 即可;

3、cell contentView 添加自定义分割线 custom_lineview。如上所述,add 在 contentView 上的subView,系统会自动处理控件的颜色值,所以即使自定义添加了 custom_lineview,高亮时也会消失。

根据 stackoverflow issue 可以通过设置layer的背景颜色阻止系统处理。但是我测试发现对 UIView控件这样设置不起作用。

另一种解决方案是在 custom_lineView 的 drawRect() 方法中处理,通过给 layer.contents 传一条直线路径的 CGImage,即可阻止系统处理。

github demo

你可能感兴趣的:(iOS Tableview,高亮状态下使separatorLine不消失的自定义方案)