如果你不知道高亮过程是怎么回事,那么单元格的高亮过程可能会显得非常复杂和令人困惑。我曾经非常困惑并进行了一些实验。以下是我的研究笔记,可以帮助某些人(如果有任何补充或反驳,请评论,我将尽力确认并更新):
普通“未选定”状态下:
contentView
(在 XIB 中的内容,除非你另行编码)正常绘制。
selectedBackgroundView
被隐藏。
backgroundView
可见(因此,只要 contentView 是透明的,你就可以看到 backgroundView
或者(如果你没有定义 backgroundView
)看到 UITableView
本身的背景颜色)。
当选中一个单元格时,立即执行以下操作,没有任何动画:
contentView
中的所有视图/子视图都会清除其 backgroundColor
(或设置为透明),标签等文本颜色更改为其选定的颜色。
selectedBackgroundView
变成可见状态(这个视图始终是单元格的全尺寸(自定义框架将被忽略,如果需要,请使用子视图)。同时请注意,某些原因导致 subViews
的 backgroundColor
不会显示,也许它们像 contentView
一样设置为透明)如果你没有定义 selectedBackgroundView
,那么 Cocoa 就会创建/插入蓝色(或灰色)渐变背景,并为你显示这个背景)。
backgroundView
不变。
当取消选择单元格时,开始一个动画以去除高亮:
selectedBackgroundView
的 alpha 属性从 1.0(完全不透明)动画到 0.0(完全透明)。
backgroundView
再次不变(因此动画看起来像是 selectedBackgroundView
和 backgroundView
之间的交叉淡化效果)。
contentView
只有在动画完成后才会以“未选定”状态重新绘制,并且其子视图的 backgroundColor
再次变得可见(这可能会导致你的动画看起来很糟糕,所以建议你不要在 contentView
中使用 UIView.backgroundColor
)。
结论:
如果你需要一个 backgroundColor
在高亮动画中保持不变,请勿使用 UIView
的 backgroundColor
属性,而是可以尝试(可能是在 tableview:cellForRowAtIndexPath:
中):
具有背景颜色的 CALayer:
UIColor *bgColor = [UIColor greenColor]
CALayer* layer = [CALayer layer]
layer.frame = viewThatRequiresBGColor.bounds
layer.backgroundColor = bgColor.CGColor
[cell.viewThatRequiresBGColor.layer addSublayer:layer]
或者是一个CAGradientLayer:
UIColor *startColor = [UIColor redColor]
UIColor *endColor = [UIColor purpleColor]
CAGradientLayer* gradientLayer = [CAGradientLayer layer]
gradientLayer.frame = viewThatRequiresBGColor.bounds
gradientLayer.colors = @[(id)startColor.CGColor, (id)endColor.CGColor]
gradientLayer.locations = @[[NSNumber numberWithFloat:0],[NSNumber numberWithFloat:1]]
[cell.viewThatRequiresBGColor.layer addSublayer:gradientLayer]
我还使用了CALayer.border技术来为自定义的UITableView分割线提供样式:
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorView.layer.borderColor = [UIColor redColor].CGColor;
separatorView.layer.borderWidth = 1.0;
[cell.contentView addSubview:separatorView];