通过animateWithDuration修改Xib中的约束没有动画效果

animateWithDuration方法中修改约束后要调用layoutIfNeeded方发刷新页面,使修改生效,否则会直接显示最终结果,而没有动画效果。

layoutIfNeeded方法的对象一般为目标View的父View。
[UIView animateWithDuration:0.3 animations:^{
    self.scrollViewTopOffset.constant = 0;
    [self.view layoutIfNeeded];
}];
动画 UIView animateWithDuration 使用详解

在ios4.0及以后鼓励使用animateWithDuration方法来实现动画效果。当然,以往的begin/commit的方法依然使用,下面详细解释一下animateWithDuration的使用方法。

函数原型:

  • (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations + (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion + (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion
    其中,

duration为动画持续的时间。
animations为动画效果的代码块。
下面是可以设置动画效果的属性:

frame
bounds
center
transform
alpha
backgroundColor
contentStretch

关于layoutIfNeeded方法的选择:
setNeedsLayout

标记为需要重新布局,异步调用layoutIfNeeded刷新布局,不立即刷新,在下一轮runloop结束前刷新,对于这一轮runloop之内的所有布局和UI上的更新只会刷新一次,layoutSubviews一定会被调用。

layoutIfNeeded

如果有需要刷新的标记,立即调用layoutSubviews进行布局(如果没有标记,不会调用layoutSubviews)。

animateWithDuration方法的调用还有一个注意点

animateWithDuration方法调用不应写在viewDidLoad方法中,应将代码块放到viewDidAppear方法中,否则会没有动画效果。

猜你喜欢

转载自blog.csdn.net/weixin_34092370/article/details/87483077