UISegmentControl 是按钮视图控制器,功能类似于UIButton
使用注意事项:
1 初始化时,必须通过设置其按钮标题数进行初始化
2 初始化后,按钮均是未被选中状态,可设置任一个按钮为选中状态,默认选中后不可再次点击
3 标题和图标只能二选一,不能同时设置
4 按钮的索引坐标是从0~N开始计算取值的
5 按钮响应方法通过识别值的变化进行响应,即 UIControlEventValueChanged
一 基本属性
// 1.1 实例化
NSArray *items = @[@"商品****详情", @"商品规格", @"售后服务"];
UISegmentedControl *segmentController = [[UISegmentedControl alloc] initWithItems:items];
// 1.2 添加到父视图
[self.view addSubview:segmentController];
// 1.3 设置原点坐标及大小
segmentController.frame = CGRectMake(10.0, 50.0, (CGRectGetWidth(self.view.bounds) - 10 * 2), 40.0);
(1)初始化后,按钮状态,默认无选中
(2)选中时的背景及边框颜色默认为蓝色
二 其他属性
// 2.1 按钮个数
NSInteger number = segmentController.numberOfSegments;
NSLog(@"number = %ld",number);
// 2.2 自适应标题宽度,默认为NO
segmentController.apportionsSegmentWidthsByContent = NO;
// 2.3 当前选中的按钮,默认无选中按钮
segmentController.selectedSegmentIndex = 0;<span style="color:#ffffff;">
</span>
(2.3)设置选中第一个按钮
// 2.4 设置边框及按钮选中状态的颜色
segmentController.tintColor = [UIColor redColor];
(2.4)设置按钮及边框选中状态颜色为红色
// 2.5 设置某个按钮的标题,设置后图标无效
[segmentController setTitle:@"京东商城的商品" forSegmentAtIndex:0];
(2.5)设置第一个按钮标题
// 2.6 获取按钮标题
NSString *title = [segmentController titleForSegmentAtIndex:0];
NSLog(@"title = %@",title);
// 2.7 设置某个按钮的宽度
[segmentController setWidth:50.0 forSegmentAtIndex:0];
// 2.8 获取某个按钮的宽度
CGFloat width = [segmentController widthForSegmentAtIndex:1];
NSLog(@"width = %@",@(width));
// 2.9 设置某个按钮是否可点击,默认为YES,即可点击
[segmentController setEnabled:NO forSegmentAtIndex:0];
(2.9)设置了第一个按钮不可点击
// 3.0 获取某个按钮是否可点击
BOOL isEnable = [segmentController isEnabledForSegmentAtIndex:0];
NSLog(@"isEnable = %@",@(isEnable));
三 添加响应方法
1 定义
<span style="font-family: Menlo;"> [segmentController addTarget:self action:@selector(segmentControllerAction:) forControlEvents:UIControlEventValueChanged];</span>
2 响应方法
- (void)segmentControllerAction:(UISegmentedControl *)segment
{
// 获取当前被点击的按钮索引
NSInteger index = segment.selectedSegmentIndex;
NSLog(@"点击了第 %@ 个按钮",@(index));
if (0 == index)
{
NSLog(@"点击了 京东商城的商品");
}
else if (1 == index)
{
NSLog(@"点击了 商品规格");
}
NSString *title = [segment titleForSegmentAtIndex:index];
if ([title isEqualToString:@"京东商城的商品"])
{
NSLog(@"点击了 京东商城的商品");
}
else if ([title isEqualToString:@"商品规格"])
{
NSLog(@"点击了 商品规格");
}
}