我有一种执行小动画动画的方法。这个动画有点像,但是每次我从风景位置调用它时它都会旋转。在模拟器处于横向状态时调用动画时,整个视图将自身旋转为纵向,然后执行动画。旋转本身不是动画,它只是突然改变而没有延迟。视图中的所有内容都会移动,所有按钮,文本字段,图像视图等等。
动画代码:
- (void)shakeView
{
CGFloat t = 8.0;
CGAffineTransform translateRight = CGAffineTransformTranslate(CGAffineTransformIdentity, 0.0, t);
CGAffineTransform translateLeft = CGAffineTransformTranslate(CGAffineTransformIdentity, 0.0, -t);
self.view.transform = translateLeft;
[UIView animateWithDuration:0.07 delay:0.0 options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat animations:^{[UIView setAnimationRepeatCount:3.0];
self.view.transform = translateRight;
}
completion:^(BOOL finished){
if (finished)
{
[UIView animateWithDuration:0.05 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{self.view.transform = CGAffineTransformIdentity;
}
completion:NULL];
}
}];
}
老实说,我对动画做的不多,所以我不知道我在这里做错了什么,更不用说我应该尝试什么,或者在哪里寻找答案。
我希望保持动画,同时保持方向。
答案 0 :(得分:1)
问题是视图已经对其进行了非身份转换。为了使视图在横向中正确显示,系统在其上应用旋转视图的变换。仅当设备位于UIDeviceOrientationPortrait时,视图的转换才是CGAffineTransformIdentity。此方向旋转仅适用于应用程序的根子级,即窗口的第一个子视图。使用以下内容初始化翻译动画时
CGAffineTransform translateRight = CGAffineTransformTranslate(CGAffineTransformIdentity, 0.0, t);
您告诉旋转的视图忽略其旋转并在纵向模式下快速回到其方向。您可以通过执行以下两项操作之一来解决此问题:
使动画视图成为根视图的子视图。这样做的好处是系统仍然可以免费处理旋转,并且您的动画没有任何机会搞砸方向更改。此外,代码最终将更简单,更易于维护。
存储视图的初始转换,并对其应用所有转换。
我会尝试在这里做#2。
- (void)shakeView
{
CGFloat t = 8.0;
//store the initial transform and use it to create the animated transforms
CGAffineTransform initialTransform = self.view.transform;
CGAffineTransform translateRight = CGAffineTransformTranslate(initialTransform, 0.0, t);
CGAffineTransform translateLeft = CGAffineTransformTranslate(initialTransform, 0.0, -t);
self.view.transform = translateLeft;
[UIView animateWithDuration:0.07
delay:0.0
options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat
animations:^{
[UIView setAnimationRepeatCount:3.0];
self.view.transform = translateRight;
}
completion:^(BOOL finished){
if (finished)
{
[UIView animateWithDuration:0.05
delay:0.0
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
//restore the initial transform
self.view.transform = initialTransform;
}
completion:NULL];
}
}];
}
注意 - 从iOS 8开始,UIWindow的根视图不再在旋转时进行转换。相反,UIWindow本身的界限会发生变化。有关此问题,请参阅此处:UIWindow frame in ios 8 different from ios 7 in Landscape