简体   繁体   English

iOS自定义UIView设计:init与layoutSubviews

[英]iOS custom UIView design: init vs layoutSubviews

I have a number of custom UIViews. 我有许多自定义UIView。

I constantly find myself initializing properties in the init of my custom view, but I also set the frame there too. 我经常发现自己在自定义视图的init中初始化属性,但是我也在那里设置了框架。

I usually leave my layoutSubviews empty. 我通常将layoutSubviews留空。 If I don't expect my view bounds to change, is it ok to have my various subview frames set in the init itself, or should I move that to layoutSubviews? 如果我不希望视图范围发生变化,可以在初始化本身中设置各种子视图框架,还是应该将其移至layoutSubviews?

I wanted to mention that one of the reasons, I do it this way is because often I find myself having to calculate the frame (size) of my custom view based on how my subviews get laid out. 我想提到的原因之一,是因为我经常不得不根据子视图的布局来计算自定义视图的框架(大小)。

I usually resize my custom view's frame after all of my subview frame sizes have been set. 通常,在设置了所有子视图框架大小之后,我通常会调整自定义视图框架的大小。

You should avoid allocating/creating your views in layoutSubviews method, because it will be called a lot of times. 您应该避免在layoutSubviews方法中分配/创建视图,因为它将被调用很多次。 You can allocate your views in your initializer methods and layout them in layoutSubviews method. 您可以在初始化方法中分配视图,并在layoutSubviews方法中对其进行布局。 But if your views' frames are non-relative to your view's bounds, then there is nothing to worry about setting their frames in your initializer methods. 但是,如果视图的框架与视图的边界无关,则无需担心在初始化方法中设置其框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM