iOS 移动view的点击事件

本文介绍如何通过Layer动画实现移动视图的动画效果,并详细解释了如何为移动中的UIView添加点击事件,包括如何准确判断点击发生在视图的不同部分。

要点:

1.Layer动画
2.hitTest:方法

改进的地方:

view内各个子view的点击判断。

代码:

1.给移动view添加Layer动画

    JHBarrageView *view = [[JHBarrageView alloc] init];
    view.frame = CGRectMake(kScreenWidth, 200, 200, 50);
    [self.view addSubview:view];
    _barrageView = view;

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.x"];
    animation.toValue = @(view.jh_w*0.5);
    animation.duration = 10;
    animation.repeatCount = 0;
    animation.fillMode = kCAFillModeForwards;
    animation.removedOnCompletion = NO;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [_barrageView.layer addAnimation:animation forKey:@"move"];

2.view的父类添加点击事件

    [self.view addGestureRecognizer:({
        [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jhTap:)];
    })];

3.点击事件判断处理

- (void)jhTap:(UITapGestureRecognizer *)tap
{
    CGPoint clickPoint =  [tap locationInView:self.view];
    //判断点是否在移动的layer中,这个可以注释掉
    //if ([_barrageView.layer.presentationLayer hitTest:clickPoint]) {
        //转换点到移动view的动画layer中
        CGPoint p = [_barrageView.layer.presentationLayer convertPoint:clickPoint fromLayer:self.view.layer];
        //再进行判断
        if (CGRectContainsPoint(_barrageView.header.layer.presentationLayer.frame, p)) {
            _clickLabel.text = @"点击了头像";
        }
        else if (CGRectContainsPoint(_barrageView.nameLabel.layer.presentationLayer.frame, p)) {
            _clickLabel.text = @"点击了名字";
        }
        else if (CGRectContainsPoint(_barrageView.textLabel.layer.presentationLayer.frame, p)) {
            _clickLabel.text = @"点击了内容";
        }
    //}
}

参考:

参考一:ios捕捉移动view的点击事件
参考二:iOS 为移动中的UIView(UIButton )添加点击事件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豪冷啊

你的鼓励是对我的认可!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值