iOS 开发之旅

父子控制器详细解析(一)

2017-09-25  本文已影响57人  刀客传奇

版本记录

版本号 时间
V1.0 2017.09.25

前言

在APP中很多时候我们都需要用到父子控制器来达到我们的需求,这个用的次数不是很频繁,但是在大的项目中搭建架构的时候还是会用到的,接下来我们就详细的解析一下父子控制器。相关代码已发到 Github - 刀客传奇

几个基本概念

1. 定义

父子控制器,指的是一个控制器通过addChildViewController:方法添加多个控制器,被添加的控制器称为子控制器,添加多个子控制器的控制器称为父控制器。

2. 父子控制器关系

3. 什么时候使用父子控制器?

当Apple提供的框架不能满足开发者的时候,考虑重新搭建框架。比如UITabBarControllertabBar默认是在底部,想要把它放到顶部或者左边,实现起来会很困难,这时考虑到模仿UITabBarController的功能,搭建新的框架可能会更简单。

4. 创建父子控制器方法

一个控制器使用addChildViewController:方法添加子控制器。

如果两个控制器的视图View是父子关系,那么这两个控制器也应该是父子关系,也就是说应该利用代码创建父子关系。

5. 父子控制器优点和注意事项

6. 父子控制器的接口及几个重要方法

下面我们要看一下父子控制器需要的几个重要方法。

/*
  If the child controller has a different parent controller, it will first be removed from its current parent
  by calling removeFromParentViewController. If this method is overridden then the super implementation must
  be called.
*/
- (void)addChildViewController:(UIViewController *)childController NS_AVAILABLE_IOS(5_0);
/*
  Removes the the receiver from its parent's children controllers array. If this method is overridden then
  the super implementation must be called.
*/
- (void)removeFromParentViewController NS_AVAILABLE_IOS5_0);
/*
  These two methods are public for container subclasses to call when transitioning between child
  controllers. If they are overridden, the overrides should ensure to call the super. The parent argument in
  both of these methods is nil when a child is being removed from its parent; otherwise it is equal to the new
  parent view controller.

  addChildViewController: will call [child willMoveToParentViewController:self] before adding the
  child. However, it will not call didMoveToParentViewController:. It is expected that a container view
  controller subclass will make this call after a transition to the new child has completed or, in the
  case of no transition, immediately after the call to addChildViewController:. Similarly,
  removeFromParentViewController does not call [self willMoveToParentViewController:nil] before removing the
  child. This is also the responsibilty of the container subclass. Container subclasses will typically define
  a method that transitions to a new child by first calling addChildViewController:, then executing a
  transition which will add the new child's view into the view hierarchy of its parent, and finally will call
  didMoveToParentViewController:. Similarly, subclasses will typically define a method that removes a child in
  the reverse manner by first calling [child willMoveToParentViewController:nil].
*/
- (void)willMoveToParentViewController:(nullable UIViewController *)parent NS_AVAILABLE_IOS(5_0);
- (void)didMoveToParentViewController:(nullable UIViewController *)parent NS_AVAILABLE_IOS(5_0);
/*
  This method can be used to transition between sibling child view controllers. The receiver of this method is
  their common parent view controller. (Use [UIViewController addChildViewController:] to create the
  parent/child relationship.) This method will add the toViewController's view to the superview of the
  fromViewController's view and the fromViewController's view will be removed from its superview after the
  transition completes. It is important to allow this method to add and remove the views. The arguments to
  this method are the same as those defined by UIView's block animation API. This method will fail with an
  NSInvalidArgumentException if the parent view controllers are not the same as the receiver, or if the
  receiver explicitly forwards its appearance and rotation callbacks to its children. Finally, the receiver
  should not be a subclass of an iOS container view controller. Note also that it is possible to use the
  UIView APIs directly. If they are used it is important to ensure that the toViewController's view is added
  to the visible view hierarchy while the fromViewController's view is removed.
*/
- (void)transitionFromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^ __nullable)(void))animations completion:(void (^ __nullable)(BOOL finished))completion NS_AVAILABLE_IOS(5_0);

一个简单实例

下面我们就看一个简单实例,三个按钮点击后选择对应的子控制器,看一下代码。

#import "ViewController.h"
#import "JJChildVCOne.h"
#import "JJChildVCTwo.h"
#import "JJChildVCThree.h"

#define kViewControllerScreenWidth     [UIScreen mainScreen].bounds.size.width
#define kViewControllerScreenHeight    [UIScreen mainScreen].bounds.size.height

@interface ViewController ()

@property (nonatomic, strong) UIViewController *currentVC;

@end

@implementation ViewController

#pragma mark -  Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //设置UI
    [self setupUI];
    
    //加子控制器
    [self setupChildVC];
}

#pragma mark -  Object Private Function

- (void)setupChildVC
{
    JJChildVCOne *childOneVC = [[JJChildVCOne alloc] init];
    childOneVC.view.backgroundColor = [UIColor redColor];
    
    JJChildVCTwo *childTwoVC = [[JJChildVCTwo alloc] init];
    childTwoVC.view.backgroundColor = [UIColor blueColor];
    
    JJChildVCThree *childThreeVC = [[JJChildVCThree alloc] init];
    childThreeVC.view.backgroundColor = [UIColor greenColor];
    
    [self addChildViewController:childOneVC];
    [self addChildViewController:childTwoVC];
    [self addChildViewController:childThreeVC];
}

- (void)setupUI
{
    for (NSInteger i = 0; i < 3; i ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *title = [NSString stringWithFormat:@"切换%d", i];
        [button setTitle:title forState:UIControlStateNormal];
        button.tag = i;
        [button addTarget:self action:@selector(buttonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = [UIFont boldSystemFontOfSize:20.0];
        
        //不同标签的差异化设置
        if (i == 0) {
            button.backgroundColor = [UIColor redColor];
        }
        else if (i == 1){
            button.backgroundColor = [UIColor blueColor];
        }
        else {
            button.backgroundColor = [UIColor greenColor];
        }
        
        [self.view addSubview:button];
        button.frame = CGRectMake(i * kViewControllerScreenWidth / 3, 0.0, kViewControllerScreenWidth / 3, 40);
    }
}

#pragma mark -  Action && Notification

- (void)buttonDidClick:(UIButton *)button
{
    UIViewController *vc = self.childViewControllers[button.tag];
    vc.view.frame = CGRectMake(0.0, 40.0, kViewControllerScreenWidth, kViewControllerScreenHeight - 40.0);
    //移除掉当前显示的控制器的view
    [self.currentVC.view removeFromSuperview];
    self.currentVC = vc;
    //把选中的控制器view显示到界面上
    [self.view addSubview:self.currentVC.view];
}

@end

下面看一下效果图

后记

未完,待续~~~

上一篇 下一篇

猜你喜欢

热点阅读