Objective-C Learning Notes - UISegmentControl 2
选中时修改 segment 图片:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize myImages,myLabels; - (void)viewDidLoad { [super viewDidLoad]; UIImage *image1 = [UIImage imageNamed:@"0.jpg"]; UIImage *image2 = [UIImage imageNamed:@"1.png"]; UIImage *image3 = [UIImage imageNamed:@"2.png"]; myImages = [[NSArray alloc]initWithObjects:image1,image2,image3, nil]; myLabels = [[NSArray alloc]initWithObjects:@"Lion",@"Elephant",@"Dog", nil]; UISegmentedControl *mySegmentControl = [[UISegmentedControl alloc]initWithItems:myLabels]; mySegmentControl.frame = CGRectMake(10, 50, 300, 300); [mySegmentControl addTarget:self action:@selector(segmentDidChange:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:mySegmentControl]; // Do any additional setup after loading the view, typically from a nib. } - (void) segmentDidChange:(id)sender{ if ([sender isKindOfClass:[UISegmentedControl class]]){ UISegmentedControl *segmentControl = sender; for (int i=0; i<segmentControl.numberOfSegments; ++i) { if (i == segmentControl.selectedSegmentIndex){ [segmentControl setImage:[myImages objectAtIndex:i] forSegmentAtIndex:i]; }else{ [segmentControl setTitle:[myLabels objectAtIndex:i] forSegmentAtIndex:i]; } } } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (strong,nonatomic) NSArray *myLabels,*myImages; @end
不知道为什么图片显示不出来......