美文网首页
iOS 移动view的点击事件

iOS 移动view的点击事件

作者: 豪冷 | 来源:发表于2019-07-31 10:06 被阅读0次

    要点:

    • 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 )添加点击事件

    相关文章

      网友评论

          本文标题:iOS 移动view的点击事件

          本文链接:https://www.haomeiwen.com/subject/nexzrctx.html