2015-10-14 78 views
0

我想通过使用分段控制器切换2 uiviews,但我似乎无法得到它的窍门。使用UISegmentedControl切换UIViews

- (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]; 

    } 
} 

当我运行此代码时,分段控件不显示在任何视图上。我试着拿出线:

[contentView2 addSubview:segmentedControl];

但现在第二个UIView显示黑色而不是黄色,只有第一个UIView显示UISegmented Control。我是IOS的初学者,任何帮助将不胜感激。

鉴于didload

回答

1

....删除此行..

[contentView addSubview:segmentedControl]; 
    [contentView2 addSubview:segmentedControl]; 

&添加以下行...

[self.view addsubview:contentView ]; 
[self.view addsubview:contentView2 ]; 
[self.view addsubview:segmentedControl]; 
+0

视图中添加的主视图......你在段控制添加视图....所以这就是为什么不显示任何视图 –

+0

谢谢。这工作:) – av993

+0

非常感谢你... –