James
James

Reputation: 301

Creating a UIView Programatically in viewDidLayoutSubviews

I want to programatically create UIViews which depend on the size of the bounds of self.view. I've put the code to create the UIViews in viewDidLayoutSubviews.

The problem is that viewDidLayoutSubviews is called multiple times when my viewController appears on screen, thus creating multiple instances of the UIView. I'm thinking that this could be solved by using some sort of flag.

Is there a better way to do this? Should the code be put somewhere else in the view controller lifecycle?

Upvotes: 0

Views: 1176

Answers (2)

Lei Zhang
Lei Zhang

Reputation: 634

In the method of viewDidLayoutSubviews, you can get the updated the frame size for UIControls, after that you can programatically create UIViews in the viewDidAppear.

While I do not think you should create UIViews in viewDidLoad method, in autolayout you can not get correct size of views until viewDidLayoutSubviews has been called.

Upvotes: 0

Sunil Chauhan
Sunil Chauhan

Reputation: 2084

You should not put creating UIView code in viewDidLayoutSubviews, you should create it in viewDidLoad instead. You can put view frame update code in viewDidLayout. Or you can use autolayout so you don't need any view update code manually. I prefer autolayout.

Upvotes: 5

Related Questions