iOS常用方法——动画点击事件的实现

动画的实现我们一般都用UIImageView,比如之前博客中的直线等动画,现在想要给在动的的图片添加一个点击事件。
当时做这个功能的时候试过很多方法,但是有些确实不行,有些时候我不知道别人在写博客的时候是怎么想的,或者真的没有亲自试过,或者是代码太老了无效?有些文章中给出的代码确实跟文章介绍的功能不一致,我觉得最好是自己试过,保证能实现自己所说的功能,这是最基本的。毕竟别人找资料要一个一个试,分享本来是一件好事,基本的责任心也是应该要有的。所以我写博客的时候,一般都是边写demo,边写文章,不是亲试有效的代码不会贴出来。
回归正题,实现思路是在动画的父View上添加UITapGestureRecognizer手势来实现。主要代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor cyanColor];
    [self setupAnimationView];
}

-(void)setupAnimationView{
    UIImageView * shipImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image_cruise_ship"]];
    shipImageView.frame = CGRectMake(self.view.frame.size.width, 260, shipImageView.image.size.width/5.0, shipImageView.image.size.height/5.0);
    shipImageView.tag = 1000;
    //直线动画
    CABasicAnimation* moveAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
    moveAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(self.view.frame.size.width,260)];
    moveAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(-150,260)];
    moveAnimation.duration = 30;
    moveAnimation.removedOnCompletion = NO;
    moveAnimation.repeatCount = MAXFLOAT;
    [shipImageView.layer addAnimation:moveAnimation forKey:@"shipAnimation"];
    [self.view addSubview:shipImageView];
    //添加点击事件
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(animationShipClick:)];
    //注意:点击事件是添加在父View上的,不是直接加在UIImageView上的,因为UIImageView在运动中交互是关闭的
    [self.view addGestureRecognizer:tap];
}

-(void)animationShipClick:(UITapGestureRecognizer *)gesture{
    //获取动画的UIImageView
    UIImageView * moveShipImageView = (UIImageView *)[self.view viewWithTag:1000];
    //获取动画UIImageView在view上的位置
    CGPoint touchPoint = [gesture locationInView:self.view];
    if ([moveShipImageView.layer.presentationLayer hitTest:touchPoint]) {
        //点击了动画区域
        UIAlertView * alterView = [[UIAlertView alloc] initWithTitle:nil message:@"动画点击" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alterView show];
        //TODO:在这里实现动画点击方法
    }else{
        //点击了动画之外的区域
        UIAlertView * alterView = [[UIAlertView alloc] initWithTitle:nil message:@"view点击" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alterView show];
    }
}

需要注意的是点击手势是要加在动画的superView上的,以上代码可直接运行,效果如下图:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值