【问题标题】:adding subView to the UINavigationBar and removing it将 subView 添加到 UINavigationBar 并将其删除
【发布时间】:2013-10-09 18:33:58
【问题描述】:

我正在尝试创建 UINavigationBar 的自定义外观。当用户将应用置于横向时,navigationBar 应该被一个 Image 覆盖。当旋转回纵向时,我希望删除视图(图像)。除了删除它之外,下面的代码一切正常。如果我将代码放在同一个 if 语句中,我可以删除视图,但如果我把它放在 else if 语句中,则不会发生任何事情。我错过了什么吗? /问候

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

  }

}

【问题讨论】:

    标签: iphone ios uiview uinavigationbar subview


    【解决方案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"]];
    }
    

    现在您可以为其添加和删除。

    【讨论】:

      【解决方案2】:

      你试过 UIAppearance 吗?

        [[UINavigationBar appearance] setBackgroundImage:nil barMetrics:UIBarMetricsDefault];
        [[UINavigationBar appearance] setBackgroundImage:image barMetrics:UIBarMetricsLandscapePhone];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-05
        • 2010-11-28
        • 2018-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-15
        • 1970-01-01
        相关资源
        最近更新 更多