直接上代码:
UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"黄色", @"红色", @"(~﹃~)~zZ", @"☺"]];
segmentControl.frame = CGRectMake(30, 100, CGRectGetWidth(self.view.bounds) - 60, 40);
segmentControl.selectedSegmentIndex = 1;
[self handleSegmentAction:segmentControl];
segmentControl.tintColor = [UIColor blackColor];
UIImage *firstImage = [[UIImage imageNamed:@"2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[segmentControl setImage:firstImage forSegmentAtIndex:0];
[segmentControl addTarget:self action:@selector(handleSegmentAction:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:segmentControl];
[segmentControl release];
- (void)handleSegmentAction:(UISegmentedControl *)sender {
switch (sender.selectedSegmentIndex) {
case 0:
self.view.backgroundColor = [UIColor yellowColor];
NSLog(@"黄色");
break;
case 1:
self.view.backgroundColor = [UIColor redColor];
NSLog(@"红色");
break;
case 2:
self.view.backgroundColor = [UIColor blueColor];
NSLog(@"蓝色");
break;
case 3:
self.view.backgroundColor = [UIColor greenColor];
NSLog(@"绿色");
break;
}
NSLog( @"%s", __FUNCTION__ ) ;
}