Reputation: 71
I am trying to switch between 2 uiviews by using a segmented controller but I can't seem to get the hang of it.
- (void)viewDidLoad {
[super viewDidLoad];
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
contentView = [[UIView alloc] initWithFrame:applicationFrame];
contentView.backgroundColor = [UIColor greenColor];
self.view = contentView;
CGRect applicationFrame2 = [[UIScreen mainScreen] applicationFrame];
contentView2 = [[UIView alloc] initWithFrame:applicationFrame2];
contentView2.backgroundColor = [UIColor yellowColor];
NSArray *itemArray = [NSArray arrayWithObjects: @"Player 1", @"Player 2", nil];
segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(12, 100, 350, 30);
[segmentedControl addTarget:self action:@selector(segmentAction) forControlEvents: UIControlEventValueChanged];
[contentView addSubview:segmentedControl];
[contentView2 addSubview:segmentedControl];
}
-(void) segmentAction {
if (segmentedControl.selectedSegmentIndex == 0) {
[contentView setHidden:NO];
[contentView2 setHidden:YES];
}
if (segmentedControl.selectedSegmentIndex == 1) {
[contentView setHidden:YES];
[contentView2 setHidden: NO];
}
}
When I run this code the Segmented Control doesn't show on any of the views. I tried taking out the line:
[contentView2 addSubview: segmentedControl];
but now second UIView shows black instead of yellow and only the first UIView shows the UISegmented Control. I am a beginner at IOS and any help would be greatly appreciated.
Upvotes: 0
Views: 33
Reputation: 1704
in view didload.... remove this lines..
[contentView addSubview:segmentedControl];
[contentView2 addSubview:segmentedControl];
& add following lines...
[self.view addsubview:contentView ];
[self.view addsubview:contentView2 ];
[self.view addsubview:segmentedControl];
Upvotes: 1