UI第八节——UISegmentedControl

时间:2021-02-04 07:54:31

- (void)viewDidLoad {
    [super viewDidLoad];

    NSArray *items = @[@"消息", @"电话"];
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:items];
    segment.frame = CGRectMake(40, 100, 295, 30);

    // 添加一个新的Item到segment中
    [segment insertSegmentWithTitle:@"眼神" atIndex:1 animated:YES];
    
    // 设置选择的Item
    segment.selectedSegmentIndex = 0;
    
    // 主题颜色
    segment.tintColor = [UIColor orangeColor];

    // 添加事件
    [segment addTarget:self action:@selector(segmentValueChanged:) forControlEvents:UIControlEventValueChanged];
    
    [self.view addSubview:segment];
}

- (void)segmentValueChanged:(UISegmentedControl *)segment
{
    // 当前选择哪一人Item
    // selectedSegmentIndex 当前选的是哪一个
    NSString *selectedIndexTitle = [segment titleForSegmentAtIndex:segment.selectedSegmentIndex];
    NSLog(@"%@", selectedIndexTitle);
}