创建控件
- (void)createSegmentControl
{
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"所有", @"分类", @"进行中"]];
segmentedControl.frame = CGRectMake(80, 30, 180, 30);
segmentedControl.selectedSegmentIndex = 0;
[segmentedControl setTintColor:[UIColor redColor]];
[segmentedControl setTitle:@"不是所有" forSegmentAtIndex:0];
[segmentedControl setImage:[UIImage imageNamed:@"2.png" ] forSegmentAtIndex:2];
NSLog(@"button共同拥有%lu个", segmentedControl.numberOfSegments);
[self addSubview:segmentedControl];
[segmentedControl release];
[segmentedControl addTarget:self action:@selector(segmentedControlAction:) forControlEvents:UIControlEventValueChanged];
}
实现点击事件
- (void)segmentedControlAction:(UISegmentedControl *)sender
{
// 通过 selectedSegmentIndex 推断点中了哪一个 Segment
/*
if (sender.selectedSegmentIndex == 0) {
NSLog(@"所有");
} else if (sender.selectedSegmentIndex == 1) {
NSLog(@"分类");
} else if (sender.selectedSegmentIndex == 2) {
NSLog(@"进行中");
}
*/
switch (sender.selectedSegmentIndex) {
case 0:
{
NSLog(@"所有");
break;
}
case 1:
NSLog(@"分类");
break;
case 2:
NSLog(@"进行中");
break;
default:
break;
}
}