简单的分段控制器 实现在导航条上
导入新建控制器
#import "ViewController.h"
#import "Controller1.h"
#import "Controller2.h"
@interface ViewController (){
Controller1 *V1;
Controller2 *V2;
}
- (void)viewDidLoad {
[super viewDidLoad];
//设置控件几个
NSArray*array = [NSArray arrayWithObjects:@"Controller1",@"Controller2",nil];
UISegmentedControl *segC = [[UISegmentedControl alloc]initWithItems:array];
//开始时默认选中下标(第一个下标默认是0)
segC.selectedSegmentIndex = 0;
//添加分段控制器的点击事件
[segC addTarget:self action:@selector(add:) forControlEvents:UIControlEventValueChanged];
//控件渲染色(也就是外观字体颜色)
segC.tintColor= [UIColor blackColor];
//按下是否会自动释放:
self.navigationItem.titleView = segC;
V1 = [[Controller1 alloc]init];
V2 = [[Controller2 alloc]init];
//设置点进去第一个控制器
[self.view addSubview:V1.view];
}
//switch判断点进去的控制器
- (void)add:(UISegmentedControl *)segmt{
int index = (int)segmt.selectedSegmentIndex;
switch(index) {
case 0:{
[self.view addSubview:V1.view];
[V2.view removeFromSuperview];
}
break;
case 1:{
[self.view addSubview:V2.view];
[V1.view removeFromSuperview];
}
break;
default:
break;
}
}