UI基础 - UISegmentedControl

■ 简言

1. UISegmentedControl 分段控件提供一栏按钮,也被称为按钮栏

■ 使用方式

 1 #import "ViewController.h"
 2 #import "AppDelegate.h"
 3 @interface ViewController()
 4 @end
 5 
 6 @implementation ViewController
 7 - (void)viewDidLoad {
 8     [super viewDidLoad];
 9     self.view.backgroundColor = [UIColor blackColor];
10     
11     NSArray *titles = [NSArray arrayWithObjects:@"男人",@" ? ",@"女人", nil];
12     // 传入的数组可以是字符串,也可以是 UIImage对象 图片
13     UISegmentedControl *segmented = [[UISegmentedControl alloc] initWithItems:titles];
14     [segmented setFrame:CGRectMake(20, 100, self.view.frame.size.width - 40, 45)];
15     segmented.selectedSegmentIndex = 1;// 默认选中下标:?
16     [segmented setSelectedSegmentTintColor:[UIColor greenColor]]; // 选中背景颜色
17     [segmented setWidth:80 forSegmentAtIndex:1];    // 给某一位置的分段单独指定宽度,其余宽度均分给每个分段
18     segmented.backgroundColor = [UIColor cyanColor];// 背景颜色
19     segmented.momentary = NO;// 默认 NO:YES 表示按钮按下后很快恢复(撤销选中状态)
20     
21     // 选中字体颜色
22     NSDictionary *selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20],
23                                              NSForegroundColorAttributeName: [UIColor redColor]};
24     [segmented setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];
25     // 常态字体颜色
26     NSDictionary *unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
27                                                NSForegroundColorAttributeName: [UIColor yellowColor]};
28     [segmented setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
29     [segmented addTarget:self action:@selector(changeSegment:) forControlEvents:UIControlEventValueChanged];
30     [self.view addSubview:segmented];
31     
32     // UISegmentedControl 在 iOS 13中有了新的外观,用于更改分段控件的颜色的现有代码不再像以前那样工作
33     // 在 iOS 13之前,您可以设置 tintColo;在 iOS 13 后,tintColor 什么也不做
34     segmented.tintColor = [UIColor orangeColor];
35 }
36 
37 - (void)changeSegment:(UISegmentedControl *)segment{
38     NSLog(@"选中下标:%ld   选中标题:%@",segment.selectedSegmentIndex,[segment titleForSegmentAtIndex:segment.selectedSegmentIndex]);
39     // 修改标题
40     if (segment.selectedSegmentIndex == 1) {
41         [segment setTitle:@"宝宝" forSegmentAtIndex:1];
42     }else{
43         [segment setTitle:@"?" forSegmentAtIndex:1];
44     }
45 }
46 
47 @end

运行效果:selectedSegmentIndex = 1

 

posted on 2018-04-08 16:13  低头捡石頭  阅读(308)  评论(0编辑  收藏  举报

导航