Frame calculations in `viewDidLayoutSubviews`

青春壹個敷衍的年華 提交于 2019-12-05 11:29:54

The app gets only one didLayoutSubviews per draw (up to that point, view state changes are just noted with setNeedsLayout). In that sense, didLayoutSubviews is your idea of didCompleteLayoutOfSubviews. After the draw, if another view state change happens, the layout is incomplete again.

In other words, number of didLayout calls doesn't depend on the number of subview adds or frame changes, it depends on the number of draws (not to be confused with the run loop). Before a draw, if the needsLayout flag has been set, layoutSubviews and then didLayoutSubviews will be called exactly once, no matter how much the view hierarchy has been rearranged.

You should always re-layout for the dimension your view currently has.

You set the frames, then rotate the device. Do you need to recompute the frames? Sure you do, the bounds size has changed! You are making dangerous assumptions with your framesAreSet.

If performance really is key for you, you may want to cache the computed frames an some dictionary in invalidate those if the bounds size changes.

But you are certainly not going to get away with performing layout only once.

An alternative would be to make the view controller's view an instance of a custom class and override -layoutSubviews in there.

You can calculate frame in viewDidLayoutSubviews method using dispatch once token (GCD) that if frames are initialized once this will not get inside your dispatchonce block.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!