ios 实现选中时阴影效果

ios UI控件在选中高亮的时候一般都会添加高亮效果,以提示用户当前选中的视图,提高用户体验。

UIButton 和 UITableViewCell 系统都有设置高亮时的阴影效果的API,这里不多做赘述。 像UIImageView,UIView,或者是这些控件组合起来的类似卡片类型控件。这些控件可以通过添加UITapGestureRecognizer达到和按钮一样的效果,这是就需要在这些控件上添加选中的时的高亮效果。实现这种效果的方法有两种:

1.在这些空间上加一个可以改变背景颜色的view,然后监听他的  touchesBegin/end/cancel 方式,来改变背景颜色。具体代码如下:

// 开始触摸时添加背景色
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    self.backgroundColor = [UIColor colorWithHexString:@"f8f8f8"];
}
// 结束时清除背景色
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    if (self.shouldShowSelectedBg) {
       self.backgroundColor = [UIColor clearColor];
    }
}
// 手势移动的时候清除背景色
- (void)touchesCancelled:(NSSet<UITouch *> *)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<UITouch *> *)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<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.selectedBgView removeFromSuperview];
}

- (void)touchesCancelled:(NSSet<UITouch *> *)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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值