我正在使用AdBannerView
更新一个旧应用,当没有广告时,它会滑出屏幕。出现广告时,它会在屏幕上滑动。基本的东西。
旧样式,我将帧设置在动画块中。
新样式,我对自动布局约束有一个IBOutlet
,它确定Y
的位置,在这种情况下,它是距父 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;
}
附带一提,我已经检查了无数次,并且这是在主线程上执行的。
最佳答案
两个重要注意事项:
layoutIfNeeded
。苹果实际上建议您在动画块之前调用一次,以确保所有未完成的布局操作均已完成self.view
)上专门调用它,而不是在附加了约束的 subview 上调用它。这样做将更新所有受约束的 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;
}
迅捷3
UIView.animate(withDuration: 5) {
self._addBannerDistanceFromBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}