AutoLayout动画

平常我们实现动画都是直接调整frame,使用autolayout之后,建议调整constraint

AutoLayout动画

 

如上图的约束都是可以通过拖动,拖到.h或者.m文件中的,也是通过IBOutlet标识的

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

 [UIView animateWithDuration:1.0 animations:^{

        

        if (self.view.tag) {

            _xConstraint.constant = 20.0;

        } else {

            _xConstraint.constant = self.view.bounds.size.width - 120.0;

        }

    }];

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

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

    [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,方法告诉视图,当其子视图发生变化的时候,更新布局,然后再将这个动作包裹到动画代码中

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

 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];

    }];

 

你可能感兴趣的:(layout)