2015-10-14 66 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

非常感謝你... –

相關問題