首页 文章

使用UIView animate和CGAffineTransform时会发生奇怪的行为

提问于
浏览
2

我在项目中创建了一些动画 . 基本上,我使用UIView animate和CGAffineTransform,但是发生了一件非常奇怪的事情,我不知道 . 希望有人能帮我解决这个问题 . 提前致谢 .

这是奇怪的事情:用户点击一个按钮后,按钮滑出屏幕,另外两个按钮在屏幕上滑动(我只是改变了这些按钮的中心点来实现这个动画) . 并且,一段时间后,屏幕上的视图开始抖动(我使用CGAffineTransform来实现这一点) .

此时,奇怪的事情发生了 - 先前滑出屏幕的按钮再次显示在原始位置,另外两个按钮消失(没有动画,只是显示并消失) .

以下是相关代码,

1)按钮滑动并滑动动画相关代码

- (IBAction)start:(id)sender
{
    // 1. Slide in cancel and pause button
    [UIView animateWithDuration:0.5f animations:^{
        [startButton setCenter:CGPointMake(startButton.center.x + 300.0f, startButton.center.y)];
        [cancelButton setCenter:CGPointMake(cancelButton.center.x + 300.0f, cancelButton.center.y)];
        [pauseButton setCenter:CGPointMake(pauseButton.center.x + 300.0f, pauseButton.center.y)];
    } completion:^(BOOL finished) {
        if (finished) {
            NSLog(@"Move finished");
        }
    }];
}

2)摇动动画相关代码的视图

- (void)shakeView:(UIView *)viewToShake
{
    CGFloat t = 2.0;
    CGAffineTransform translateRight  = CGAffineTransformTranslate(CGAffineTransformIdentity, t, 0.0);
    CGAffineTransform translateLeft = CGAffineTransformTranslate(CGAffineTransformIdentity, -t, 0.0);

    viewToShake.transform = translateLeft;

    [UIView animateWithDuration:0.07 delay:0.0 options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat animations:^{
        [UIView setAnimationRepeatCount:2.0];
        viewToShake.transform = translateRight;
    } completion:^(BOOL finished) {
        if (finished) {
            [UIView animateWithDuration:0.05 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                viewToShake.transform = CGAffineTransformIdentity;
            } completion:nil];
        }
    }];
}

2 回答

  • 7

    这并不奇怪,这是自动布局的常见问题 . 如果通过更改框架移动UI元素,则只要发生需要布局视图的其他内容,移动的视图将恢复到其约束定义的位置 . 要修复它,您需要关闭自动布局,或通过更改约束而不是帧来制作动画 .

  • 1

    我在我的测试项目中尝试过你的代码 . 问题可能是因为您在xib中使用 Autolayout .
    请检查您的xib文件并取消选中 Autolayout 属性 .

相关问题