IOS开发中的小知识点整理

iOS刷新view方法小结

2017-04-13  本文已影响727人  叶子扬

视图刷新是常有的事情,数据的更新、视图的创建、添加、滚动、frame的改变,都更刷新相关,掌握刷新的窍门,能提高应用的性能和用户体验。

layoutSubviews

以下几个动作都会触发layoutSubviews

看看 Apple 给出的描述:
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 thelayoutIfNeeded method.

翻译成白话文,就是要重写layoutSubviews这个方法,但是不要直接调用,而是用setNeedsLayout来触发它执行刷新方法,但是这个方法并不会立即刷新,而是在下一次运行循环的时候才执行。若要立即更新,补上layoutIfNeeded方法就OK啦

sizeToFit和 sizeThatFits:

sizeToFit刷新调用者,给调用者一个最合适的size,这个size会紧紧的围绕着这个视图,例如:label调用它,那么label的size将会是最合适的size:刚好容纳下所有文字(注:如果label设置了numberOfLines:,那么只会给出对应的行数的size而不是全部)
sizeThatFits:不会刷新调用者的frame,但是会返回最合适的size(最合适的意思同上)
具体用法见。。。

drawRect:和setNeedsDisplay

drawRect:提供绘制功能,如果要刷新绘画,不能直接调用,而是通过setNeedsDisplay来触发
setNeedsLayout:。他会标记为需要重新布局,异步调用layoutIfNeeded刷新布局,不立即刷新,但layoutSubviews一定会被调用

setNeedsDisplayInRect:(CGRect)invalidRect:

layoutSubviewslayoutIfNeeded

根据Apple官方文档layoutIfNeeded方法应该是这样的:

上一篇 下一篇

猜你喜欢

热点阅读