设为首页 加入收藏

TOP

创建父子控制器
2017-10-13 10:29:05 】 浏览:4363
Tags:创建 父子 控制器

小码哥大神的代码,确实精简!

1、最终结果如下面三个图,点击one,two,three,分别出现3个不同的控制器

直接代码:(三个控制器自己创建)

 1 #import "ViewController.h"
 2 #import "ZWOneViewController.h"
 3 #import "ZWTwoViewController.h"
 4 #import "ZWThreeViewController.h"
 5 @interface ViewController ()
 6 /** 正在显示的控制器 */
 7 @property (weak, nonatomic)UIViewController *showingVC;
 8 @end
 9 @implementation ViewController
10 
11 - (void)viewDidLoad {
12     [super viewDidLoad];
13     //添加到子控制器上
14     [self addChildViewController:[[ZWOneViewController alloc] init]];
15     [self addChildViewController:[[ZWTwoViewController alloc] init]];
16     [self addChildViewController:[[ZWThreeViewController alloc] init]];
17 }
18 - (IBAction)buttonClick:(UIButton *)button {
19     //移除当前显示的控制器
20     [self.showingVC.view removeFromSuperview];
21     //获得控制器的位置索引
22     NSUInteger index = [button.superview.subviews indexOfObject:button];
23     //添加控制器View
24     self.showingVC = self.childViewControllers[index];
25     //设置尺寸
26     self.showingVC.view.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64);
27     //添加到控制器上
28     [self.view addSubview:self.showingVC.view];
29 }
30 @end

 

注:1、扩展性非常好,直接数组中添加需要添加的控制器

  2、由于是索引,一定要注意三个控制器的顺序,否则会出现点击后出现其它控制器。如下图:

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇多线程简单总结 下一篇电工助手 V1.4

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目