自定义控制器的切换-动画

效果:

//
//  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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值