2013-10-09 78 views
0

我正在尝试创建自定义外观的UINavigationBar。当用户将应用放在横向位置时,navigationBar应该用一个Image覆盖。当旋转回肖像时,我想要删除视图(图像)。除了删除它之外,一切工作都正常。如果我将代码放在相同的if语句中,我可以删除View,但如果将其放入else if语句中,则不会发生任何反应。我错过了什么吗? /关注将子视图添加到UINavigationBar并将其删除

- (void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation { 

    UIView *v = [[UIView alloc]init]; 

    if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) 
{ 

    v.frame = CGRectMake(0,0,480,44); 
    v.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"navbar25g.png"]]; 
    [self.view addSubview:v]; 
    //[v removeFromSuperview]; <----- works if I put it here 

    NSLog(@"LANDSCAPE");//load the landscape view 

} 
    else if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) 
{ 
      [v removeFromSuperview]; <----- Not working 


     NSLog(@"PORTRAIT"); //load the portrait view 

    } 

} 

回答

1

你不能删除它的原因是每次你进入创建UIView * v的新实例的方法。

创建一个实例变量,然后将视图分配给该实例变量。分配后,您可以根据需要删除或添加。

如果你不想用一个实例变量,那么你可以给视图中的代码即

UIView *v = nil; 

v = [self.view viewForTag:1000]; 

if (!v) { 
    v = [[UIView alloc] init]; 
    v.tag = 1000; 
    v.frame = CGRectMake(0, 0, 480, 44); 
    v.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"navbar25g.png"]]; 
} 

现在你可以做你的添加和删除它。

0

你试过UIAppearance?

[[UINavigationBar appearance] setBackgroundImage:nil barMetrics:UIBarMetricsDefault]; 
    [[UINavigationBar appearance] setBackgroundImage:image barMetrics:UIBarMetricsLandscapePhone]; 
相关问题