How to use autoresize on 2 UIViewControllers? [clo

2019-09-26 08:09发布

问题:

I have 2 UIViewControllers:

UIViewControllers1
UIViewControllers2

UIViewControllers2.view is added as subView to UIViewControllers1.view.

And the problem is that UIViewControllers2.view doesn't want to autoresize when UIViewControllers1.view is resizing (UIViewControllers1 setFrame:frame).

[UIViewControllers1.view setAutoresizesSubViews:YES]
[UIViewControllers1.view setAutoResizeMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)]
[UIViewControllers1.view addSubview:UIViewControllers2.view];

How to fix it?

回答1:

Well, part of the problem is that this is illegal:

[UIViewControllers1.view addSubview:UIViewControllers2.view];

You must never just wantonly add one view controller's view to another view controller's view. There is only one way in which that is allowed outside of a built-in parent-child structure that does it for you (UINavigationController, UITabBafController, UIPageViewController), and that is when you create your own elaborate custom parent-child structure - and you are not doing that. The architecture needed for doing that is described in my book here:

http://www.apeth.com/iOSBook/ch19.html#_container_view_controllers

To be clear, there is nothing whatever wrong with adding a view to another view! The ability to make views come and go is crucial to iOS. What's wrong is that you must not add a view controller's view to another view, except under the parent-child view controller architecture, built-in or custom.