我正在使用 AdBannerView
更新旧应用程序,当没有广告时,它会滑出屏幕。当有广告时,它会在屏幕上滑动。基本的东西。
旧样式,我将帧设置在动画 block 中。
新样式,我有一个 IBOutlet
到自动布局约束,它确定 Y
位置,在这种情况下它是与 super View 底部的距离,并修改常量:
- (void)moveBannerOffScreen {
[UIView animateWithDuration:5 animations:^{
_addBannerDistanceFromBottomConstraint.constant = -32;
}];
bannerIsVisible = FALSE;
}
- (void)moveBannerOnScreen {
[UIView animateWithDuration:5 animations:^{
_addBannerDistanceFromBottomConstraint.constant = 0;
}];
bannerIsVisible = TRUE;
}
横幅移动,完全符合预期,但没有动画。
更新:我重新看了WWDC 12 talk Best Practices for Mastering Auto Layout其中包括动画。它讨论了如何使用 CoreAnimation 更新约束:
我已尝试使用以下代码,但得到完全相同的结果:
- (void)moveBannerOffScreen {
_addBannerDistanceFromBottomConstraint.constant = -32;
[UIView animateWithDuration:2 animations:^{
[self.view setNeedsLayout];
}];
bannerIsVisible = FALSE;
}
- (void)moveBannerOnScreen {
_addBannerDistanceFromBottomConstraint.constant = 0;
[UIView animateWithDuration:2 animations:^{
[self.view setNeedsLayout];
}];
bannerIsVisible = TRUE;
}
顺便说一句,我已经检查了很多次,这是在 main 线程上执行的。
最佳答案
两个重要说明:
你需要在动画 block 中调用layoutIfNeeded
。苹果实际上建议你在动画 block 之前调用一次,以确保所有待处理的布局操作都已完成
您需要在 父 View (例如 self.view
)上专门调用它,而不是附加了约束的 subview 。这样做将更新所有个受约束的 View ,包括为可能被约束到您更改约束的 View 的其他 View 设置动画(例如, View B 附加到 View A 的底部,而您刚刚更改了 View A顶部偏移,并且您希望 View B 使用它进行动画处理)
试试这个:
Objective-C
- (void)moveBannerOffScreen {
[self.view layoutIfNeeded];
[UIView animateWithDuration:5
animations:^{
self._addBannerDistanceFromBottomConstraint.constant = -32;
[self.view layoutIfNeeded]; // Called on parent view
}];
bannerIsVisible = FALSE;
}
- (void)moveBannerOnScreen {
[self.view layoutIfNeeded];
[UIView animateWithDuration:5
animations:^{
self._addBannerDistanceFromBottomConstraint.constant = 0;
[self.view layoutIfNeeded]; // Called on parent view
}];
bannerIsVisible = TRUE;
}
swift 3
UIView.animate(withDuration: 5) {
self._addBannerDistanceFromBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
https://stackoverflow.com/questions/12622424/