答案 0 :(得分:0)
我有答案使用UIContainer
在ios中动态显示两个ViewControllers
,
我有创建BaseViewController和两个viewControllers
(GreenViewController和OrangeViewController),让我们看下面的图像是
并baseView
插入了两个UIButton
(绿色和橙色按钮),UIContainerView
,来源位于下方,
BaseViewController.h
档案:
@property (weak, nonatomic) IBOutlet UIView *containView;
@property (weak, nonatomic) UIViewController *currentViewController;
BaseViewController.m
档案:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_currentViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"GreenViewController"];
_currentViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
[self addChildViewController:_currentViewController];
[self addSubview:_currentViewController.view toView:_containView];
}
- (void)addSubview:(UIView *)subView toView:(UIView*)parentView {
[parentView addSubview:subView];
NSDictionary * views = @{@"subView" : subView,};
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[subView]|"
options:0
metrics:0
views:views];
[parentView addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[subView]|"
options:0
metrics:0
views:views];
[parentView addConstraints:constraints];
}
- (void)cycleFromViewController:(UIViewController*) oldViewController
toViewController:(UIViewController*) newViewController {
[oldViewController willMoveToParentViewController:nil];
[self addChildViewController:newViewController];
[self addSubview:newViewController.view toView:self.containView];
[newViewController.view layoutIfNeeded];
// set starting state of the transition
newViewController.view.alpha = 0;
[UIView animateWithDuration:0.5
animations:^{
newViewController.view.alpha = 1;
oldViewController.view.alpha = 0;
}
completion:^(BOOL finished) {
[oldViewController.view removeFromSuperview];
[oldViewController removeFromParentViewController];
[newViewController didMoveToParentViewController:self];
}];
}
绿色按钮操作位于
之下- (IBAction)greenViewAction:(id)sender {
UIViewController *newViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"GreenViewController"];
newViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
[self cycleFromViewController:self.currentViewController toViewController:newViewController];
self.currentViewController = newViewController;
}
橙色按钮操作位于
之下- (IBAction)orangeViewAction:(id)sender {
UIViewController *newViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"OrangeViewController"];
newViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
[self cycleFromViewController:self.currentViewController toViewController:newViewController];
self.currentViewController = newViewController;
}
它为我工作,请参阅下面的输出,
希望它有用