UISegmentedControl——分段控件

时间:2024-11-04 22:06:23

  分段控件,提供了一组按钮,但是只能激活一个。通过UIControlEventValueChanged事件实现与用户的交互,并通过selectedSegmentIndex判断当前选定的控件,通过titleForSegmentAtIndex可以获取当前选中控件的标题。

- (void)viewDidLoad {

[super viewDidLoad];

//分段控件中各控件的标题

NSArray *array = @[@"未支付",@"已支付",@"已到货"];

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:array];

segmentedControl.frame = CGRectMake(20, 20, self.view.bounds.size.width - 40, 40);

//设置未选中控件的背景色和选择控件的字体颜色

segmentedControl.backgroundColor = [UIColor yellowColor];

//设置选中控件的背景色和未选中控件的字体颜色

segmentedControl.tintColor = [UIColor blueColor];

//设置初始状态下,第一个控件为选中状态

segmentedControl.selectedSegmentIndex = 0;

//设置选择控件触发的事件

[segmentedControl addTarget:self action:@selector(selectSegmentedControl:) forControlEvents:UIControlEventValueChanged];

//设置第二个控件的标题

[segmentedControl setTitle:@"hehe" forSegmentAtIndex:1];

//在第二个控件后插入一个按钮

[segmentedControl insertSegmentWithTitle:@"呵呵" atIndex:2 animated:YES];

[self.view addSubview:segmentedControl];

}

- (void)selectSegmentedControl:(UISegmentedControl*)segmentedControl {

//获取选中状态的标题

NSString *str = [segmentedControl titleForSegmentAtIndex:segmentedControl.selectedSegmentIndex];

NSLog(@"%ld:%@",segmentedControl.selectedSegmentIndex,str);

}