What is the correct way to display multiple ViewCo

2019-08-22 02:55发布

Recently, I am working on a project which have multiple ViewControllers, the controllers's view hierarchy need to display on screen at same time, the link below(it is a picture) is my design.

http://www.lazycatdesign.com/stuff/question.png

MainViewController is a Container ViewController, I add the MenuViewController and PictureViewController to it like this:

// Create the controllers
MainViewContorller* mainVC = [[MainViewController alloc] init];
MenuViewController* menuVC = [[MenuViewController alloc] init];
PictureViewController* pictureVC = [[PictureViewController alloc] init];

// add MenuViewController to MainViewController as its child controller
[mainVC addChildViewController:menuVC];
[mainVC.view addSubview:menuVC.view];
[menuVC didMoveToParentViewController:mainVC];

// add PictureViewController to MainViewController as its child controller
[mainVC addChildViewController:pictureVC];
[mainVC.view addSubview:pictureVC.view];
[pictureVC didMoveToParentViewController:mainVC];

Menu View and Picture View is now displayed on screen, the problem is only the Picture View can response the UI Event(such as the Tap Gesture). It seems only the last view hierarchy I add to Container ViewController can response UI Event, why? and what is the correct way to display multiple ViewController's view hierarchy in a Container ViewContorler?

1条回答
孤傲高冷的网名
2楼-- · 2019-08-22 03:13

Finally, the problem is solved, as rdelmar said, I forget to set the frames to the subviews, apple's document View Controller Programming Guide for iOS (page 117) also mention this, the codes should be:

// Create the controllers
MainViewContorller* mainVC = [[MainViewController alloc] init];
MenuViewController* menuVC = [[MenuViewController alloc] init];
PictureViewController* pictureVC = [[PictureViewController alloc] init];

// add MenuViewController to MainViewController as its child controller
[mainVC addChildViewController:menuVC];
[menuVC setFrame:frameOfMenuView];          // set the correct frame to menu view
[mainVC.view addSubview:menuVC.view];       // add menu view as sub view to main view
[menuVC didMoveToParentViewController:mainVC];

// add PictureViewController to MainViewController as its child controller
[mainVC addChildViewController:pictureVC];
[pictureVC setFrame:frameOfPictureView];    // set the correct frame to picture view
[mainVC.view addSubview:pictureVC.view];    // add picture view as sub view to main view
[pictureVC didMoveToParentViewController:mainVC];
查看更多
登录 后发表回答