今天学习的是UISegmentedControl,相当于一个切换的分区栏,例如看小说会分最新,最热等,可以用此控件来进行切换
1.初始化(用数组进行初始化)并添加到视图上
// 数组中初始化必须是字符串 或者 图片
// 如果选用图片初始化 必须使用镂空图NSArray *stringArray = @[@"第一段",@"第二段",@"第三段"];// 分段按钮UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:stringArray];segmentedControl.frame = CGRectMake(20, 100, 300, 50);segmentedControl.backgroundColor = [UIColor greenColor];[self.view addSubview:segmentedControl];[segmentedControl release];
2.设置默认选中(从0开始)
segmentedControl.selectedSegmentIndex = 1;
3.修改选中的颜色
segmentedControl.tintColor = [UIColor brownColor];
4.修改中间段的宽度
[segmentedControl setWidth:200 forSegmentAtIndex:1];
下面一个实例来说明怎么用UISegmentedControl切换页面:
UIImage *image1 = [UIImage imageNamed:@"01-refresh"];UIImage *image2 = [UIImage imageNamed:@"02-redo"];UIImage *image3 = [UIImage imageNamed:@"03-loopback"];NSArray *imageArray = @[image1, image2, image3];UISegmentedControl *segmentedControlImage = [[UISegmentedControl alloc] initWithItems:imageArray];segmentedControlImage.backgroundColor = [UIColor orangeColor];segmentedControlImage.frame = CGRectMake(40, 300, 300, 50);segmentedControlImage.tintColor = [UIColor purpleColor];segmentedControlImage.selectedSegmentIndex = 0;[self.view addSubview:segmentedControlImage];[segmentedControlImage release];// 添加一个点击事件// 选取UIControlEventValueChanged 实际上是检测了索引的变化[segmentedControlImage addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];// 将三控制器设置为根视图控制器的子控制器self.grayVC = [[GrayViewController alloc] init];[self addChildViewController:self.grayVC];[self.view addSubview:self.grayVC.view];[_grayVC release];self.blueVC = [[BlueViewController alloc] init];[self addChildViewController:self.blueVC];[self.view addSubview:self.blueVC.view];[_blueVC release];self.greenVC = [[GreenViewController alloc] init];[self addChildViewController:self.greenVC];[self.view addSubview:self.greenVC.view];[_greenVC release];// 最前面的应该是segment// 然后是默认选中按钮对应的视图[self.view bringSubviewToFront:self.grayVC.view];[self.view bringSubviewToFront:segmentedControlImage];}- (void)segmentedAction:(UISegmentedControl *)segmentedControl
{// 需求 判断出 点击了哪个分段按钮// 每个分段按钮 控制一个界面 每个界面是一个控制器来控制 并且可以切换界面NSLog(@"点了第%ld个",segmentedControl.selectedSegmentIndex);// 通过索引切换不同的界面switch (segmentedControl.selectedSegmentIndex) {case 0:[self.view insertSubview:self.grayVC.view belowSubview:segmentedControl];break;case 1:[self.view insertSubview:self.greenVC.view belowSubview:segmentedControl];break;case 2:[self.view insertSubview:self.blueVC.view belowSubview:segmentedControl];break;default:break;}
}