问题
My scenario is that right now my app uses 12 ViewControllers. Each one has two ContainerViews which hold the same set of controls (I'll call them control groups) and I show them via segues. So far this is working however, I have to layout and set constraints for the same two ContainerViews 12 times - once for each VC. And if I add another VC, then I have to lay them out again, etc. If I change any part of my layout then I have to modify all 12 again and again - it's not really scalable.
It seems to me it would be easier if the two control groups are on one VC which also contains a ContainerView. Then, if the ContainerView could switch between each of the twelve views it would be a lot easier to maintain.
For example something like this mockup:
This mockup shows the two control containers "Upper" and "Lower" on the same VC. in between would be the ContainerView which would show the required VC.
Of course, ContainerViews can only embed a single VC, so the closest solution I've seen is to put 12 ContainerViews on top of each other - seems quite messy still.
I'm not necessarily requiring the use of a ContainerView - however, there are some nice features such as restricting the size of the VC and making it adhere to its dimensions which makes laying out the contents easier.
How can I get this kind of structure and behavior? (Note: I would like to be able to use the Storyboard too)
回答1:
From the project I am working:
Add as many container views as you want to your main view controller. Than in your code, change the alpha
values to show/hide them. Like this:
@IBOutlet weak var timelineContainerView: UIView!
@IBOutlet weak var albumsContainerView: UIView!
@IBAction func journeySegmentedControlValueChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
timelineContainerView.alpha = 1.0
albumsContainerView.alpha = 0.0
case 1:
timelineContainerView.alpha = 0.0
albumsContainerView.alpha = 1.0
default:
break
}
}
If you have a lot of controllers, you may want to use an IBOutlet group.
来源:https://stackoverflow.com/questions/53549918/how-to-use-one-containerview-to-show-multiple-viewcontrollers