切换控件-UISegmentedControl

2016-12-08  本文已影响0人  youfengHE_youf
- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建UISegmentedControl
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"视频", @"声音",@"图片"]];
    segmentedControl.frame = CGRectMake(40, 100, 300, 40);
    [self.view addSubview:segmentedControl];
    // 默认选中下标为1的item
    segmentedControl.selectedSegmentIndex = 1;
}
    // 默认选中下标为1的item
    segmentedControl.selectedSegmentIndex = 1;
    // 设置点击按钮是否选中
    segmentedControl.momentary = YES;
    // 插入一个切换模块按钮,这些有一个平滑的效果
    // 插入背景为hyf图片的按钮
    [segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"hyf"] atIndex:1 animated:YES];
    // 插入标题为新增的按钮
    [segmentedControl insertSegmentWithTitle:@"新增" atIndex:0 animated:YES];
    // 删除操作
    [segmentedControl removeSegmentAtIndex:1 animated:YES];
    // 删除所有的模块按钮
    [segmentedControl removeAllSegments];
    // 修改指定下标模块按钮的标题
    [segmentedControl setTitle:@"修改" forSegmentAtIndex:1];
    // 修改指定下标模块按钮的背景图片
    [segmentedControl setImage:[UIImage imageNamed:@"hyf改"] forSegmentAtIndex:1];
    // 自动根据内容计算模块按钮的宽度
    segmentedControl.apportionsSegmentWidthsByContent = YES;
- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建UISegmentedControl
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"视频", @"声音",@"图片"]];
    segmentedControl.frame = CGRectMake(40, 100, 300, 40);
    [self.view addSubview:segmentedControl];
    // 默认选中下标为1的item
    segmentedControl.selectedSegmentIndex = 1;
   // 自动根据内容计算模块按钮的宽度
    segmentedControl.apportionsSegmentWidthsByContent = YES;
   // 添加触发方法
    [segmentedControl addTarget:self action:@selector(click:) forControlEvents:UIControlEventValueChanged];
}
// 点击修改背景颜色
-(void)click:(UISegmentedControl *)seg {
    // 获取当前选中的按钮编号
    NSInteger index = seg.selectedSegmentIndex;
    // 根据获取到的index,修改背景颜色
    switch (index)
    {
        case 0:
            self.view.backgroundColor = [UIColor redColor]; break;
        case 1: 
            self.view.backgroundColor = [UIColor yellowColor]; break;
        case 2:
            self.view.backgroundColor = [UIColor blueColor]; break;
        default:  break;  
   }
}
上一篇下一篇

猜你喜欢

热点阅读