效果实现如下所示:
实现代码如下:
#import "ViewController.h"
#import "ViewController1.h"
#import "ViewController2.h"
#import "ViewController3.h"
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
@interface ViewController ()
@property (nonatomic,strong) UIViewController *currentVc;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor yellowColor];
[self creatUI];
[self addChildVC];
}
- (void)addChildVC{
[self addChildViewController:[[ViewController1 alloc]init]];
[self addChildViewController:[[ViewController2 alloc]init]];
[self addChildViewController:[[ViewController3 alloc]init]];
}
- (void)creatUI{
CGFloat width = kScreenWidth / 3;
for (NSInteger i =0 ; i < 3; i++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(i * width,0,width,100);
button.backgroundColor = [UIColor purpleColor];
[button setTitle:[NSString stringWithFormat:@"按钮%ld",i + 1] forState:UIControlStateNormal];
button.tag = i+ 1;
//生成随机颜色
button.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];
[button addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
}
- (void)pressBtn:(UIButton *)button{
/*移除当前控制器*/
[self.currentVc.view removeFromSuperview];
//NSInteger index = [button.superview.subviews indexOfObject:button];
//根据tag值设置当前控制器
self.currentVc = self.childViewControllers[button.tag - 1];
//设置尺寸
self.currentVc.view.frame = CGRectMake(0, 100, kScreenWidth, kScreenHeight);
//添加到控制器上
[self.view addSubview:self.currentVc.view];
}