AutoLayout动画

日常咱们实现动画都是直接调整frame,使用autolayout以后,建议调整constraint布局

 

如上图的约束都是能够经过拖动,拖到.h或者.m文件中的,也是经过IBOutlet标识的动画

若是你写成下面的代码, 发现动画是不生效的spa

 [UIView animateWithDuration:1.0 animations:^{
        
        if (self.view.tag) {
            _xConstraint.constant = 20.0;
        } else {
            _xConstraint.constant = self.view.bounds.size.width - 120.0;
        }
    }];

你发现你添加的视图是直来直去的,没有动画code

其实须要使用下面的代码,来改变约束,产生动画blog

    [UIView animateWithDuration:1.0 animations:^{
        
        if (self.view.tag) {
            _xConstraint.constant = 20.0;
        } else {
            _xConstraint.constant = self.view.bounds.size.width - 120.0;
        }
        // 告诉自动布局系统,若是布局变化,更新布局
        
        [self.view layoutIfNeeded];
    }];

 

经过layoutIfNeeded,方法告诉视图,当其子视图发生变化的时候,更新布局,而后再将这个动做包裹到动画代码中

或者下面的代码也能够,先改变约束,而后将通知视图刷新的代码写到动画块里animation

 if (self.view.tag) {
        _xConstraint.constant = 20.0;
    } else {
        _xConstraint.constant = self.view.bounds.size.width - 120.0;
    }

    [UIView animateWithDuration:1.0 animations:^{
        // demoView setFrame;
        // demoView setCenter;
        // 告诉自动布局系统,若是布局变化,更新布局
        
        [self.view layoutIfNeeded];
    }];
相关文章
相关标签/搜索