UISegmented用法

UISegmentedControl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
NSArray *subjectArray = [[NSArray alloc]initWithObjects:@"英语",@"语文",@"数学",nil];//初始化UISegmentedControl的数组
//UISegmentedControl
UISegmentedControl *subjectSegmented = [[UISegmentedControl alloc]initWithItems:subjectArray];//数据填充
subjectSegmented.frame = CGRectMake(0, 0, DF_WIDTH/2, 44);
subjectSegmented.segmentedControlStyle = UISegmentedControlStylePlain;//设置样式(总共有四种样式)
for(int i=0; i<[subjectArray count]; i++){//设置当前默认选中的选项
if([self.subject isEqualToString:self.subjectArray[i]]){
subjectSegmented.selectedSegmentIndex = i;
break;
}
}
self.navigationview.tintColor = [UIColor colorWithHexString:@"#ff393a"];//边框和字体颜色
[self.navigationview addSubview:self.subjectSegmented];
[subjectSegmented addTarget:self action:@selector(changeSubject:) forControlEvents:UIControlEventValueChanged];//点击动作
[subjectSegmented mas_makeConstraints:^(MASConstraintMaker *make) {//这里使用了相对布局,可以忽略
make.centerX.equalTo(self.navigationview);
make.centerYWithinMargins.equalTo(self.navigationview).with.offset(padding.top);
}];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//切换科目
-(void)changeSubject:(id)sender{
UISegmentedControl* control = (UISegmentedControl*)sender;//利用UISegmentedControl来控制选中选项时的操作
switch (control.selectedSegmentIndex) {
case 0:
self.subjectSegmented.selectedSegmentIndex = 0;
self.navTitle = [self.subjectArray[0] stringByAppendingString:@"课本"];
break;
case 1:
self.subjectSegmented.selectedSegmentIndex = 1;
self.navTitle = [self.subjectArray[1] stringByAppendingString:@"课本"];
break;
case 2:
self.subjectSegmented.selectedSegmentIndex = 2;
self.navTitle = [self.subjectArray[2] stringByAppendingString:@"课本"];
break;
default:
break;
}
//以下是其他操作,比如数据更新之类的
[self setSubjectEdition];
[self.rightButton setTitle:self.edition forState:(UIControlStateNormal)];
[self initData];
[self.tableView reloadData];
}