关于layoutSubviews那些事

其实layoutSubviews是个让我们容易忽视的方法,可能会因为在里面写的话代码麻烦,可能因为你不用手写代码,可能因为觉得没必要,总之这个方法其实还是蛮重要的。
  我们一般习惯在initWithFrame里初始化布局代码。其实这样很不好,在initWithFrame写的代码没有复用性,当父视图更改布局的时候,initWithFrame里布局的子视图布局还是原来的样子。所以苹果提供了专门写布局的layoutSubviews方法。
来看下官方文档:

The default implementation of this method does nothing on iOS 5.1 and earlier. Otherwise, the default implementation uses any constraints you have set to determine the size and position of any subviews.
Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want. You can use your implementation to set the frame rectangles of your subviews directly.
You should not call this method directly. If you want to force a layout update, call the setNeedsLayout method instead to do so prior to the next drawing update. If you want to update the layout of your views immediately, call the layoutIfNeeded method.
苹果说了布局就在layoutSubviews这里面写,而且这个方法不能直接通过调用方法名的方式调用,如果想重新布局,就调用setNeedsLayout方法。如果想立刻更新布局,就调用layoutIfNeeded方法。
那layoutSubviews什么时候会被调用呢?
1.init初始化不会触发layoutSubviews
2.当frame不为0的时候,addSubview会触发layoutSubviews
3.当frame发生改变的时候会调用。
4.创建scrollview的时候,一开始就会走,当scrollview发生滚动的时候也会走。
5.改变子视图的布局,也会调用父视图的此方法。
所以initWithFrame里面初始化子视图控件,在layoutSubviews布局代码是非常优雅的和有必要的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值