ios - 使用 UIView 动画和 CGAffineTransform 时会发生奇怪的行为

标签 ios animation uiview cgaffinetransform animatewithduration

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

奇怪的是: 用户点击一个按钮后,按钮滑出屏幕,另外两个按钮在屏幕上滑动(我只是改变了这些按钮的中心点来实现这个动画)。并且,一段时间后,屏幕上的 View 开始晃动(我使用 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) view shaking 动画相关代码

- (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];
        }
    }];
}

最佳答案

这并不奇怪,这是一个常见的问题 自动布局。如果您通过更改框架来移动 UI 元素,那么一旦发生其他需要布局 View 的事情,移动的 View 将恢复到其约束定义的位置。要修复它,您需要关闭自动布局,或者通过更改约束而不是框架来制作动画。

关于ios - 使用 UIView 动画和 CGAffineTransform 时会发生奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18245878/

相关文章:

javascript:如何实现动画?

ios - 如何获取使用自动布局的 UIView 的 x、y、宽度、高度

ios - Swift:在与其他 View Controller 相同的上下文中呈现 View Controller ?

ios - 如何将底部和右侧边框添加到自定义 CollectionView

ios - 在 json 中返回的错误解码数组 - swift

iphone - UIView类中addSubview和insertSubview的区别

ios - 在父 UIView 中移动 UIView (UIPanGestureRecognizer)

ios - 转到位于标签栏和导航栏内的 View Controller

firefox - CSS3 动画只适用于 webkit?

python - Contourf 和 quiver Animation with Basemap Python