Crash when using (animation) blocks in switch stat

2020-03-24 08:46发布

问题:

This code works (if-statement with animations):

// works
if (_camOrientation == UIDeviceOrientationPortrait) {
    [UIView animateWithDuration:0.5f animations:^(void){
        [_distanceView setTransform:CGAffineTransformMakeRotation(degreesToRadian(0.0))];
    }];
} else if (_camOrientation == UIDeviceOrientationLandscapeLeft) {
    [UIView animateWithDuration:0.5f animations:^(void){
        [_distanceView setTransform:CGAffineTransformMakeRotation(degreesToRadian(90.0))];
    }];
}

This also works (switch-statement without animations):

// works
switch (_camOrientation) {
    case UIDeviceOrientationPortrait:
        [_distanceView setTransform:CGAffineTransformMakeRotation(degreesToRadian(0.0))];
        break;

    case UIDeviceOrientationLandscapeLeft:
        [_distanceView setTransform:CGAffineTransformMakeRotation(degreesToRadian(90.0))];
        break;

    default:
        break;
}

This one crashes (switch-statement with animation):

// crashes
switch (_camOrientation) {
    case UIDeviceOrientationPortrait:
        [UIView animateWithDuration:0.5f animations:^(void){
            [_distanceView setTransform:CGAffineTransformMakeRotation(degreesToRadian(0.0))];
        }];
        break;

    case UIDeviceOrientationLandscapeLeft:
        [UIView animateWithDuration:0.5f animations:^(void){
            [_distanceView setTransform:CGAffineTransformMakeRotation(degreesToRadian(90.0))];
        }];
        break;

    default:
        break;
}

Why can't I use animation blocks in a switch statement?!?

回答1:

You should be able to :)

Try adding { } around your cases like this :

case UIDeviceOrientationPortrait: {
    [UIView animateWithDuration:0.5f animations:^void{
        [_distanceView setTransform:CGAffineTransformMakeRotation(0.0)];
    }];
    break;
}