获取CABasicAnimation的CompletionBlock

Joa*_*nes -2 core-animation objective-c ios

我对Objective-C的经验不多.我试图在用户按下按钮后结束动画.在viewDidLoad我添加了这个:

 UILongPressGestureRecognizer *recoginzer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onPress:)];
 [_buttonStart addGestureRecognizer:recoginzer];
Run Code Online (Sandbox Code Playgroud)

然后在我用来setCompletionBlock确定动画何时结束的方法中,但它不起作用.

-(void)onPress:(UILongPressGestureRecognizer*)longpress {

if (longpress.state == UIGestureRecognizerStateBegan) {

    circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(2, 2, _buttonStart.frame.size.width-4, _buttonStart.frame.size.height-4) cornerRadius:(_buttonStart.frame.size.width/2)-8].CGPath;
    circle.fillColor = [UIColor clearColor].CGColor;
    circle.strokeColor = [UIColor whiteColor].CGColor;
    circle.lineWidth = 2.5;
    [_buttonStart.layer addSublayer:circle];


    [CATransaction begin];
    CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    drawAnimation.duration            = 3.0;
    drawAnimation.repeatCount         = 1.0;
    drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    drawAnimation.toValue   = [NSNumber numberWithFloat:1.0f];
    drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    [circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];

    [CATransaction setCompletionBlock:^{
            NSLog(@"DONE");
        }];

    [CATransaction commit];


} else if (longpress.state == UIGestureRecognizerStateEnded || longpress.state == UIGestureRecognizerStateCancelled || longpress.state == UIGestureRecognizerStateFailed) {

    [circle removeFromSuperlayer];
    NSLog(@"long press OUT");

}
}
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的支持

Sul*_*han 5

您必须setCompletionBlock在添加动画之前使用.

文档(强调我的):

一旦此事务组随后添加的所有动画完成(或已被删除),保证在(在主线程上)调用的完成块对象.

[CATransaction begin];

[CATransaction setCompletionBlock:^{
    NSLog(@"DONE");
}];

[circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];

[CATransaction commit];
Run Code Online (Sandbox Code Playgroud)