How to call [self addSubView]?

I have a custom view to which I need to add a couple of routines programmatically. What is the best place to create and add these subzones? Apple docs say:

If your view class manages one or more integral subzones, do the following: Create these sub-items during the sequence of initialization of the views.

This is a little incomprehensible to me. Should I handle this in initWithFrame , initWithCoder or somewhere else?

Please note that here I am not talking about controllers, this is a view that needs to be initialized independently.

+6
source share
4 answers

initWithFrame is a method that you call to create a UIView programmatically, and initWithCoder is called when a UIView is initialized from XIB.

So, it all depends on how you are going to create your own containing view. A way to cover all cases:

 - (id) initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])){ [self setUpSubViews]; } return self; } - (id) initWithCoder:(NSCoder*)aDecoder { if ((self = [super initWithCoder:aDecoder])){ [self setUpSubViews];//same setupv for both Methods } return self; } - (void) setUpSubViews { //here create your subviews hierarchy } 
+9
source

Follow these steps: take the method that is the designated initializer for your view. That is, it is the most customizable (for example, the argument itself) init ... method, which calls every other initializer. For example, it could be -initWithFrame: as usual. Then execute this method as follows:

 - (id) initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { // add new views here, for example: UIImageView *imageView = [[UIImageView alloc] initWithImage:anImage]; [self addSubview:imageView]; [imageView release]; } return self; } 
+3
source

Typically, you should create a view and [self addSubView] in the viewdidload / viewwillappear of the parent view controller if you want to constantly display the view. You can also install it if you are with it. In some other scenario, for example, if you want to display a view when you click a button or some other actions, you must add a subview accordingly.

0
source

By integral, they mean either important or massive. viewDidLoad works just fine, but for really big or important things, initialization methods are the way to go.

0
source

Source: https://habr.com/ru/post/905072/


All Articles