半透明的UINavigationBar无法扩展到屏幕顶部

时间:2016-04-24 05:10:55

标签: ios uinavigationcontroller uinavigationbar

我想制作一个带红色的半透明UINavigationBar(适用于iOS9),我发现以下代码是必不可少的:

    navController.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
    navController.navigationBar.shadowImage = UIImage()
    navController.navigationBar.backgroundColor = UIColor(red: 1.0,green: 0.3,blue: 0.3,alpha: 0.9)
    navController.navigationBar.translucent = true

如果我只创建一个UINavigationBar(而不是创建一个UINavigationController),它可以正常工作,但它看起来像我创建了一个UINavigationController。

enter image description here 我发现罪魁祸首是navController.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) 行,但是如果我删除它,那个栏就像这样:

enter image description here 那么我该如何解决这个问题呢? (我正在以编程方式创建UINavigationController,并为我无法嵌入图像带来的不便表示歉意)

1 个答案:

答案 0 :(得分:0)

修改

您需要对UINavigationBar进行子类化,以获得所需颜色的半透明背景。看看这个答案:

https://stackoverflow.com/a/19043174/2082569

此处添加必要的代码以供参考:

@interface UnderlayNavigationBar : UINavigationBar

@end

@interface UnderlayNavigationBar ()
{
    UIView* _underlayView;
}

- (UIView*) underlayView;

@end

@implementation UnderlayNavigationBar

- (void) didAddSubview:(UIView *)subview
{
    [super didAddSubview:subview];

    if(subview != _underlayView)
    {
        UIView* underlayView = self.underlayView;
        [underlayView removeFromSuperview];
        [self insertSubview:underlayView atIndex:1];
    }
}

- (UIView*) underlayView
{
    if(_underlayView == nil)
    {
        const CGFloat statusBarHeight = 20;    //  Make this dynamic in your own code...
        const CGSize selfSize = self.frame.size;

        _underlayView = [[UIView alloc] initWithFrame:CGRectMake(0, -statusBarHeight, selfSize.width, selfSize.height + statusBarHeight)];
        [_underlayView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
        [_underlayView setBackgroundColor:[UIColor colorWithRed:1.0f green:0.3f blue:0.3f alpha:1.0f]];
        [_underlayView setAlpha:0.7f];
        [_underlayView setUserInteractionEnabled:NO];
    }

    return _underlayView;
}

@end

UIViewController* rootViewController = ...;
UINavigationController* navigationController = [[UINavigationController alloc] initWithNavigationBarClass:[UnderlayNavigationBar class] toolbarClass:nil];
[navigationController setViewControllers:@[rootViewController]];