且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UIView 动画不一致的结果

更新时间:2023-02-01 21:53:16

您的故事板已启用自动布局.当自动布局运行时,它会根据您在情节提要中设置(或自动设置)的约束来设置视图的框架.这意味着如果您更改视图的框架,自动布局将在下次运行时撤消您的更改.

Your storyboard has autolayout enabled. When autolayout runs, it sets the frames of your views based on the constraints you set up (or that were automatically set up for you) in the storyboard. This means that if you change the frame of a view, autolayout will undo your change the next time it runs.

系统会在不同时间自动触发自动布局,包括在您滚动滚动视图时.这就是为什么您在滚动时看到视图跳回"的原因.

The system triggers autolayout automatically at various times, including when you scroll a scroll view. That's why you're seeing your view "jump back" when you scroll.

如果您不需要自动布局,您可以将其关闭(请参阅这个答案 如果您需要帮助将其关闭).然后你可以在你的故事板中使用旧的弹簧和支柱"布局系统,它允许你根据需要设置视图的框架.

If you don't need autolayout, you can turn it off (see this answer if you need help turning it off). Then you can use the older "springs and struts" layout system in your storyboard, which lets you set the frames of your views however you want.

如果您确实需要自动布局,您需要学习如何使用自动布局制作动画.有两种基本方法.一种方法是修改约束,以便自动布局将视图放置在您想要的位置,然后在动画块中执行 [view layoutIfNeeded] 以将视图动画到其新位置.另一种方法是使用 NSTimerCADisplayLink 为约束本身设置动画.

If you do need autolayout, you need to learn how to make animations work with autolayout. There are two basic approaches. One approach is to modify the constraints so that autolayout will put the view where you want, and then do [view layoutIfNeeded] in an animation block to animate the view to its new position. The other approach is to animate the constraints themselves using an NSTimer or a CADisplayLink.

WWDC 2012 视频Session 228 - 掌握自动布局的***实践"解释了您的问题,并从 30 分 45 秒开始深入讨论了这两种技术.如果您需要在自动布局中使用动画,我强烈建议您观看 WWDC 2012 中的视频以及其他与自动布局相关的视频.

The WWDC 2012 video "Session 228 - Best Practices for Mastering Auto Layout" explains your problem, and discusses these two techniques in depth, starting at 30m45s. If you need to use animation with autolayout, I highly recommend you watch the video, and the other autolayout-related videos from WWDC 2012.