how to make a programmatically generated subview conform to the bounds of the superview (iOS)?

StackOverflow https://stackoverflow.com/questions/19168358

  •  30-06-2022
  •  | 
  •  

Question

I have a containing view called containerView which is a UIView. When the app starts, it's just that view. During the course of the app's execution, I want to swap two "full-size" sub views in and out of the main containerView.

My question is, how do I make sure that the sub views fill up the entire containerView regardless of the orientation of the iPad. The containerView is 300 wide, but the height varies based on orientation.

I've tried: setting the frame of the subview's from viewDidLoad, viewWillAppear, viewDidAppear directly equal to the side of the containerView frame,

creating LayoutConstraints that force the subview to conform to the containerView's proportions from viewDidLoad, viewWillAppear, and viewDidAppear. The question here is when to apply these constraints, and since the view is removed periodically, when to reapply the constraints.

I don't know what the idiomatic approach is and I want my code to be maintainable and reusable. Am i approaching this the wrong way? Is there some other way to make sure a subview fills up its containing view?

Example Code: https://gist.github.com/Sahasrara/6817105

Was it helpful?

Solution

You should set the frame size in viewDidLayoutSubviews. By then all the autolayout nonsense has occurred.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top