Update view's frame while it's being animated

别来无恙 提交于 2019-11-29 15:40:37

This is my code to do this

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet AnimatableView *animableView;
@end

@implementation ViewController

- (void)animateAlongPath
{
    UIBezierPath * path = [UIBezierPath bezierPathWithRect:self.view.frame];

    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.duration = 10;
    animation.path = path.CGPath;
    animation.removedOnCompletion = NO;
    animation.fillMode = @"kCAFillModeForwards";
    [self.animableView.layer addAnimation:animation forKey:@"animation"];
}

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

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)animate:(id)sender {
    [self animateAlongPath];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView: [touch view]];

    CALayer * selectedlayer = (CALayer*)[self.animableView.layer.presentationLayer hitTest:location];
    if(selectedlayer != nil)
        NSLog(@"touched");
    else
        NSLog(@"dont touched");
}


@end

I hope this helps you

Short answer: You can't. In both UIView and Core Animation animations, the view/layer does not actually move as it's position appears to be animating. Instead, there is a "presentation layer" that draws the animated object as it moves.

If you want to make objects tappable while a position animation is "in flight" you have to put a tap gesture recognizer on a superview that spans the entire area the view will travel over, and then do hit testing on the presentation layer of the object that's being animated.

Edit:

I have a project on Github called iOS CAAnimation Group demo that is a working demonstration of how to use hit testing on the presentation layer to detect taps on a view that's being animated along a complex path.

The code is written in Objective-C, but it should still be an illustration of the concept and techniques. Let me know if you have trouble making sense of the Objective-C code. I'm decent at Swift, although I'm still paying the bills in mostly Objective-C, so that's the syntax I know best.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!