UITableView的默认Cell,是有点击选中的高亮背景色的,UIButton也可以通过设置不同状态的背景图片来实现高亮,那么如何给自定义视图添加高亮呢?
一个技术上可行的方法就是重写UIView的各种touches方法,自己记录点击选中,点击取消等状态,不过很繁琐。
还有一个是重写UIControl的下面四个方法,下面四个方法将点击选中,取消等状态处理简化了
//是否可以开始追踪事件
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(nullable UIEvent *)event;
//是否持续追踪事件
- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(nullable UIEvent *)event;
//事件追踪结束
- (void)endTrackingWithTouch:(nullable UITouch *)touch withEvent:(nullable UIEvent *)event; // touch is sometimes nil if cancelTracking calls through to this.
//事件追踪取消
- (void)cancelTrackingWithEvent:(nullable UIEvent *)event; // event may be nil if cancelled for non-event reasons, e.g.
具体示例
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(nullable UIEvent *)event
{
BOOL b = [super beginTrackingWithTouch:touch withEvent:event];
if (b) {
如果开始追踪,那么就高亮显示
[super setBackgroundColor:高亮色];
}
return b;
}
- (void)endTrackingWithTouch:(nullable UITouch *)touch withEvent:(nullable UIEvent *)event
{
[super endTrackingWithTouch:touch withEvent:event];
//结束追踪 恢复原始背景色
[super setBackgroundColor:原始背景色];
}
- (void)cancelTrackingWithEvent:(nullable UIEvent *)event
{
[super cancelTrackingWithEvent:event];
//取消追踪 恢复原始背景色
[super setBackgroundColor:原始背景色];
}