您的位置:首页 > 其它

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

2016-02-09 18:07 387 查看
效果:


//
//  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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: