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];
}