当您的子视图拥有自己的视图控制器时,您应该遵循自定义容器控制器模式。有关更多信息,请参阅创建自定义容器视图控制器。
假设您遵循自定义容器模式,当您想要更改“内容视图”的子视图控制器(及其关联视图)时,您可以通过以下方式以编程方式执行此操作:
UIViewController *newController = ... // instantiate new controller however you want
UIViewController *oldController = ... // grab the existing controller for the current "content view"; perhaps you maintain this in your own ivar; perhaps you just look this up in self.childViewControllers
newController.view.frame = oldController.view.frame;
[oldController willMoveToParentViewController:nil];
[self addChildViewController:newController]; // incidentally, this does the `willMoveToParentViewController` for the new controller for you
[self transitionFromViewController:oldController
toViewController:newController
duration:0.5
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
// no further animations required
}
completion:^(BOOL finished) {
[oldController removeFromParentViewController]; // incidentally, this does the `didMoveToParentViewController` for the old controller for you
[newController didMoveToParentViewController:self];
}];
当你这样做时,内容视图的控制器不需要任何委托协议接口(除了 iOS 已经提供的在自定义容器方法中管理子视图控制器)。
顺便说一句,这假设与该内容视图关联的初始子控制器是这样添加的:
UIViewController *childController = ... // instantiate the content view's controller any way you want
[self addChildViewController:childController];
childController.view.frame = ... // set the frame any way you want
[self.view addSubview:childController.view];
[childController didMoveToParentViewController:self];
如果您希望子控制器告诉父控制器更改与内容视图关联的控制器,您将:
为此定义一个协议:
@protocol ContainerParent <NSObject>
- (void)changeContentTo:(UIViewController *)controller;
@end
定义父控制器以符合此协议,例如:
#import <UIKit/UIKit.h>
#import "ContainerParent.h"
@interface ViewController : UIViewController <ContainerParent>
@end
在父控制器中实现该changeContentTo
方法(就像上面概述的那样):
- (void)changeContentTo:(UIViewController *)controller
{
UIViewController *newController = controller;
UIViewController *oldController = ... // grab reference of current child from `self.childViewControllers or from some property where you stored it
newController.view.frame = oldController.view.frame;
[oldController willMoveToParentViewController:nil];
[self addChildViewController:newController];
[self transitionFromViewController:oldController
toViewController:newController
duration:1.0
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
// no further animations required
}
completion:^(BOOL finished) {
[oldController removeFromParentViewController];
[newController didMoveToParentViewController:self];
}];
}
并且子控制器现在可以参考self.parentViewController
iOS 为您提供的属性使用此协议:
- (IBAction)didTouchUpInsideButton:(id)sender
{
id <ContainerParent> parentViewController = (id)self.parentViewController;
NSAssert([parentViewController respondsToSelector:@selector(changeContentTo:)], @"Parent must conform to ContainerParent protocol");
UIViewController *newChild = ... // instantiate the new child controller any way you want
[parentViewController changeContentTo:newChild];
}