博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ios 实现选中时阴影效果
阅读量:7058 次
发布时间:2019-06-28

本文共 2277 字,大约阅读时间需要 7 分钟。

  hot3.png

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是插在最底层的,而不是盖在最上面。

转载于:https://my.oschina.net/zhxx/blog/920454

你可能感兴趣的文章
北漂感悟一
查看>>
Python 文件操作
查看>>
fastjson序列化时不输出值为null的字段
查看>>
安卓基本常用控件: View
查看>>
设计师应该关注的科技发展方向(一)
查看>>
小博老师解析Java核心技术 ——JDBC普通增删改操作
查看>>
我的友情链接
查看>>
ELK+filebeat日志分析系统部署文档
查看>>
写给开发者看的关系型数据库设计
查看>>
struct net_device网络设备结构体详解
查看>>
cacti监控 On RHEL6
查看>>
ORACLE监听能正常启动,但实例监听不到故障应急处理一例
查看>>
我的友情链接
查看>>
Linux现在已主导Azure
查看>>
kalcaddle在线文件管理器
查看>>
思科ASA8.4.2 2层透明墙基本实施和配置用例
查看>>
第一个vue应用
查看>>
mail
查看>>
在JAVA中将项目转换为maven项目
查看>>
微信三大平台介绍
查看>>