小码哥大神的代码,确实精简!
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、由于是索引,一定要注意三个控制器的顺序,否则会出现点击后出现其它控制器。如下图: