//storyboard创建UISegmentedControl
//UISegmentedControl的value值change时,对应一个事件
- (IBAction)segmentChange:(id)sender {
UISegmentedControl *mysegment = (UISegmentedControl *)sender;
NSInteger index = mysegment.selectedSegmentIndex; //通过UISegmentedControl被选中对应的索引值,判断哪个被选中
switch (index) {
case 0:
self.myView.backgroundColor = [UIColor redColor];
break;
case 1:
self.myView.backgroundColor = [UIColor greenColor];
break;
case 2:
self.myView.backgroundColor = [UIColor blueColor];
break;
default:self.myView.backgroundColor = [UIColor whiteColor];
break;
}
}
//手动创建UISegmentedControl
- (void)viewDidLoad
{[super viewDidLoad];
//可以包含图片
NSArray *segments = [[NSArray alloc]initWithObjects:@"iphone",[UIImage imageNamed:@"111.png"],@"ipod",@"imac", nil];
self.mySegmentedControl = [[UISegmentedControl alloc]initWithItems:segments];
self.mySegmentedControl.center = self.view.center;
[self.view addSubview:self.mySegmentedControl];
[self.mySegmentedControl addTarget:self action:@selector(segmentChange:) forControlEvents:UIControlEventValueChanged];
//如果你想要用户在选中一个选项之后,该选项马上变回原始状态(就像没有 被选中一样),需要将 momentary 属性设置为 YES
self.mySegmentedControl.momentary = YES;
// self.mySegmentedControl.segmentedControlStyle =UISegmentedControlStyleBezeled;
}
- (void)segmentChange:(UISegmentedControl *)sender
{
if([sender isEqual:self.mySegmentedControl])
{
NSInteger selectedSegmentIndex = [self.mySegmentedControl selectedSegmentIndex];
NSString *selectedSegmentText = [self.mySegmentedControl titleForSegmentAtIndex:selectedSegmentIndex];
NSLog(@"Segment %ld with %@ text is selected",(long)selectedSegmentIndex,selectedSegmentText);
}
}