ios UI控件在选中高亮的时候一般都会添加高亮效果,以提示用户当前选中的视图,提高用户体验。
UIButton 和 UITableViewCell 系统都有设置高亮时的阴影效果的API,这里不多做赘述。 像UIImageView,UIView,或者是这些控件组合起来的类似卡片类型控件。这些控件可以通过添加UITapGestureRecognizer达到和按钮一样的效果,这是就需要在这些控件上添加选中的时的高亮效果。实现这种效果的方法有两种:
1.在这些空间上加一个可以改变背景颜色的view,然后监听他的 touchesBegin/end/cancel 方式,来改变背景颜色。具体代码如下:
// 开始触摸时添加背景色- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; self.backgroundColor = [UIColor colorWithHexString:@"f8f8f8"];}// 结束时清除背景色- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesEnded:touches withEvent:event]; if (self.shouldShowSelectedBg) { self.backgroundColor = [UIColor clearColor]; }}// 手势移动的时候清除背景色- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesCancelled:touches withEvent:event]; if (self.shouldShowSelectedBg) { self.backgroundColor = [UIColor clearColor]; }}
由于是单独添加了一个可变颜色的背景view,所以可以通过控制view的frame 来控制高亮时的阴影view的frame。
2.在view的touchesBegin方式触发时,当前的view 的最底部插入一个带有阴影色view,在touchesEnded/cancel 的时候把这个view移除。具体实现如下:
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; if (!self.selectedBgView) { UIView *v = [[UIView alloc] initWithFrame:self.shadowView.bounds]; self.selectedBgView = v; v.backgroundColor = [UIColor colorWithHexString:@"f8f8f8"]; } [self.bgView insertSubview:self.selectedBgView atIndex:0];}- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesEnded:touches withEvent:event]; [self.selectedBgView removeFromSuperview];}- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesCancelled:touches withEvent:event]; [self.selectedBgView removeFromSuperview];}
两种方式对比各有有优缺点。
方法1需要在view中额外加一个view 增加内存的时候,但是可以多个view 都继承与该view ,可以不用再每个view 都写一遍 touchesBegin/end/cancel 方法,减少了代码的冗余。
方法2只有在选中高亮的时候才会添加view,可以减少内存的使用,但是如果有多个view都要添加高亮效果时,需要在每个view中都写一遍类似代码,增加了代码的冗余。
鱼与熊掌不可兼得,根据情况决定使用那种方式即可。
注意:1.不能在 touchesMoved 方法中把背景view移除,否则选中之后背景view会被立即移除。
2.背景view是插在最底层的,而不是盖在最上面。