动画过程中响应事件

案列

有一个button通过动画移动到另外一个位置,希望可以在移动的过程中也能点击按钮做某件事,一般情况下我们会按照下面的方法处理

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化按钮
    button       = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    // 执行动画
    [UIView animateWithDuration:10.f
                          delay:0
                        options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         button.frame = CGRectMake(0, 468, 100, 100);
                     } completion:^(BOOL finished) {
                         
    }];
}

- (void)buttonEvent:(UIButton *)button {
    NSLog(@"do something);
}

然后在实际过程中,发现真实的情况是这样的:

  1. 在移动过程中单击按钮是没有Log输出的
  2. 单击按钮动画的终点位置(就算此时按钮在界面上的位置离终点还很远)是有Log输出的
    然而这并不是我们想要的

分析

在动画过程中界面上显示移动的是layer中的presentationLayer,而layer中的modelLayer在动画开始的那一瞬间,frame已经变成CGRectMake(0, 468, 100, 100)
换句话说,动画效果是presentationLayer改变位置的结果,而modelLayer是没有动画效果的

解决方法

touchesBegan方法中去判断当前点击的点是否在presentationLayerframe里面,在这之前应该做如下两件事

  1. 注释buttonaddTarget方法(不然会出现上面提到的情况2)
  2. 设置button.userInteractionEnabled = NO(不然在终点处button的单击会阻止触摸事件)
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    CALayer *presentationLayer = button.layer.presentationLayer;
    CALayer *modelLayer = button.layer.modelLayer;
    NSLog(@"%@", NSStringFromCGRect(presentationLayer.frame));
    NSLog(@"%@", NSStringFromCGRect(modelLayer.frame));
    
    //判断这个点是否在presentationLayer里面
    CGPoint point = [[touches anyObject] locationInView:self.view];
    if (CGRectContainsPoint(presentationLayer.frame, point)) {
        [self buttonEvent:nil];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,573评论 6 30
  • Core Animation Core Animation,中文翻译为核心动画,它是一组非常强大的动画处理API,...
    45b645c5912e阅读 3,070评论 0 21
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,147评论 5 13
  • 有了前两篇的概念基础,本篇从以下两点结合具体代码探索下CoreAnimation的一些原理。 UIView动画实现...
    正谦阅读 2,345评论 2 15
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,252评论 4 61