问题
My aim:
I am using storyboard to create the views in my App.
My aim is to have a single instance of a view that would be exposed and linked in all pages of the App. In my case if there is an App with many tabs, I want that the view would appear in all tabs and have the same state.
My attempt and doing that:
I created a view and embedded it in container views that are in the different tabs.
When opening the app the view appears and works, on all pages. However, if I make a change in one view it doesn't propagate to the other views.
In other words, in the example below if I change the state of the switch in one page, that change would not appear when I navigate to the other page (in my app I have tabs to do that).
I saw that there is a "link" option under "Traits" but that didn't help.
How can I make sure there is only one instant of the view in all tabs?
Cheers!
回答1:
As I said in my comment, you can't do this with segues, since they always create new instances. So, I think you will have to add the child controller in code to each controller that needs it. In the storyboard, you can add a subview to each controller that needs the embedded controller that acts as a placeholder. Give the controller with the switch, a freeform size, and set its size to the same size as the subviews you added to the other controllers, and uncheck the box that says "Resize View from NIB". Here is an example storyboard,
In code, you'll need to add the controller in viewDidAppear, and remove it in viewDidDisappear (so it can be added to the next controller -- it can't be in two places at once). In the controller, you'll create an instance of the controller with the switch, and in all other controllers you get a reference to that same instance. So, in the first controller,
- (void)viewDidLoad {
[super viewDidLoad];
self.embed = [self.storyboard instantiateViewControllerWithIdentifier:@"SharedVC"];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self addChildViewController:self.embed];
[self.container addSubview:self.embed.view];
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self.embed.view removeFromSuperview];
[self.embed willMoveToParentViewController:nil];
[self.embed removeFromParentViewController];
}
In all the other controllers, you need something like this in viewDidAppear (viewDidDisappear would be the same as in the first controller),
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.embed = [(FirstViewController *)self.tabBarController.viewControllers[0] embed];
[self addChildViewController:self.embed];
[self.container addSubview:self.embed.view];
}
来源:https://stackoverflow.com/questions/23728986/storyboard-how-to-link-a-single-view-to-multiple-container-views