美文网首页
Autolayout和frame

Autolayout和frame

作者: whbsspu | 来源:发表于2017-08-16 11:16 被阅读134次

    现在iOS页面布局用的最多的就是frame和Autolayout,实际上Autolayout的约束最终都是由系统转换成frame来进行布局的。而当Autolayout与frame设置上产生冲突时,则会以Autolayout的设置为准。

    跟布局相关的方法

    - (void)setNeedsLayout;
    - (void)layoutIfNeeded;
    - (void)layoutSubviews;
    

    setNeedsLayout方法标记当前view是需要重新布局的,在下一次runloop中,进行重新布局。如果想在当前的runloop中立刻更新布局,则通过调用layoutIfNeeded方法可以实现,此时系统会调用layoutSubviews,在layoutSubviews方法中,可以自己定义新的view或者改变子view的布局。

    Autolayout相关的方法

    //view的方法
    - (void)updateConstraintsIfNeeded;
    //重写view中的方法
    - (void)updateConstraints
    - (BOOL)needsUpdateConstraints
    - (void)setNeedsUpdateConstraints
    
    //重写viewController中的方法
    - (void)updateViewConstraints
    

    setNeedsUpdateConstraints只是标记当前view的约束需要在下一次runloop中更新,updateConstraintsIfNeeded如果过满足更新条件会立刻调用updateConstraints来更新约束,updateConstraints是子view需要重写的方法,来更新View的约束,最后需要调用[super updateConstraints],否则会崩。而updateViewConstraints是定义在viewController中的,方便去更新viewController对应view的约束。

    具体可以通过调用view的setNeedsUpdateConstraints来最终调用到viewController的updateViewConstraints方法来,如果没有这个方法,那么每次都要定义一个子view去重写updateConstraints方法会比较繁琐。updateConstraints和updateViewConstrains方法可以把约束的代码和和业务逻辑分开,另外性能也更好。

    为什么会有setxxxxx和xxxifNeeded方法

    setxxxxx方法可能是为了性能,没有在代码更新布局或者约束之后立刻执行,而是在下一次runloop中执行。

    xxxxIfNeeded方法则是为了在必要的时候,立刻更新约束或者布局,举个例子,有些时候同时使用动画和autolayout。

    相关文章

      网友评论

          本文标题:Autolayout和frame

          本文链接:https://www.haomeiwen.com/subject/kbfirxtx.html