0

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have to do it in code since I create a variable number of UIViews in my view controller. Also, if I created them in viewDidLoad and updated the frame in viewDidLayoutSubviews, would that not mean that I would have to have each individual UIView as a property?
You could also create your subviews in viewWillLayoutSubviews. But if you create them in viewDidLayoutSubviews, you will trigger another layout pass. Also, since a property can be an array or a dictionary, you don't have to have a separate property for every subview. What properties you need really depends on what the subviews are for and how you lay them out.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.