效果:
//
// ViewController.m
// 0209-自定义控制器的切换
//
// Created by yongkaidong on 16/2/9.
// Copyright © 2016年 com.yongkaidong. All rights reserved.
//
#import "ViewController.h"
#import "OneViewController.h"
#import "TwoViewController.h"
#import "ThreeViewController.h"
@interface ViewController ()
/** 正在显示的控制器 */
@property (nonatomic, weak) UIViewController *showingVc;
/** 用来存放子控制器的view */
@property (nonatomic, weak) UIView *contentView;
@end
@implementation ViewController
/**
* 懒加载创建用来包裹子控件view的contentView
*/
- (UIView *)contentView
{
if (_contentView == nil) {
UIView *contentView = [[UIView alloc] init];
contentView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64);
[self.view addSubview:contentView];
self.contentView = contentView;
}
return _contentView;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 通过addChildViewController添加的控制器都会存在于childViewControllers数组中
[self addChildViewController:[[OneViewController alloc] init]];
[self addChildViewController:[[TwoViewController alloc] init]];
[self addChildViewController:[[ThreeViewController alloc] init]];
}
- (IBAction)buttonClick:(UIButton *)sender
{
// 移除其他控制器的view
[self.showingVc.view removeFromSuperview];
// 获得控制器的位置(索引)
NSUInteger index = [sender.superview.subviews indexOfObject:sender];
// 当前控制器的索引
NSUInteger oldIndex = [self.childViewControllers indexOfObject:self.showingVc];
// 添加控制器的view
self.showingVc = self.childViewControllers[index];
self.showingVc.view.frame = self.contentView.bounds;
[self.contentView addSubview:self.showingVc.view];
// 动画
CATransition *animation = [CATransition animation];
animation.type = @"cube";
animation.subtype = index > oldIndex ? kCATransitionFromRight : kCATransitionFromLeft;
animation.duration = 0.5;
[self.contentView.layer addAnimation:animation forKey:nil];
}
@end