UISegmentedControl
初始化
初始化的数组中 必须是 字符串(标题) 或者图片,如果选择图片初始化,则图片必须是镂空图片
NSArray *itemArray = @[@"第一段", @"第二段", @"第三段"];
// 分段按钮, 独有的初始化方法
UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:itemArray];
位置,背景色
segmentControl.frame = CGRectMake(20, 100, 300, 50);
segmentControl.backgroundColor = [UIColor redColor];
设置默认选中(索引从零开始)
segmentControl.selectedSegmentIndex = 1;
修改选中的颜色
segmentControl.tintColor = [UIColor cyanColor];
修改指定下标段的宽度
[segmentControl setWidth:200 forSegmentAtIndex:1];
添加到视图上并释放
[self.view addSubview:segmentControl];
[segmentControl release];
添加一个点击事件
// 注意监测值变化ValueChanged (索引值的变化)
[seg addTarget:self action:@selector(segClick:) forControlEvents:(UIControlEventValueChanged)];
添加三个子视图控制器 点击SegmentedControl实现界面切换
self.secondVC = [[SecondViewController alloc] init];
[self addChildViewController:self.secondVC];
[self.view addSubview:self.secondVC.view];
[_secondVC release];
self.thirdVC = [[ThirdViewController alloc] init];
[self addChildViewController:self.thirdVC];
[self.view addSubview:self.thirdVC.view];
[_thirdVC release];
self.forthVC = [[ForthViewController alloc] init];
[self addChildViewController:self.forthVC];
[self.view addSubview:self.forthVC.view];
[_forthVC release];
// 在最前面的应该是segment
// 然后是默认选中第一界面视图 self.secondVC.view
[self.view bringSubviewToFront:self.secondVC.view];
点击方法的实现
- (void)segClick:(UISegmentedControl *)seg{
// 需求 判断出 点击了那个分段按钮
// 三段每个分段按钮控制一个界面 每个界面是一个controller控制器 并且可以切换界面
NSLog(@"点了..%ld个",seg.selectedSegmentIndex);
// 通过索引切换不同的页面
switch (seg.selectedSegmentIndex) {
case 0:
{
[self.view bringSubviewToFront:self.secondVC.view];
}
break;
case 1:
{
[self.view bringSubviewToFront:self.thirdVC.view];
}
break;
case 2:
{
[self.view bringSubviewToFront:self.forthVC.view];
}
default:
break;
}
// 每次都把seg放到最上面
[self.view bringSubviewToFront:seg];
}