isklikas isklikas - 3 months ago 16
Objective-C Question

drawRect on a UINavigationBar subclass makes the status bar go black

I have the same issue as the thread here. I can manage to make the Status Bar Visible by making the text white but this isn't my goal. I also mean to color on top of the bar, like all navigation bars do. I've been able to achieve this by adding the shapes I want with views, under layoutSubviews, however this way you can't interact or see the UINavigationItem. Code:

- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor yellowColor] setFill];
UIRectFill(rect);


This is the result:

enter image description here

This is the bast that can be achieved with drawRect:

enter image description here

And this happens if you do it under layoutSubviews:

enter image description here

As you can see, the back text, the arrow, are all lost. So I'm really looking for a way to make drawRect work! Thanks in advance for your help!

Answer

First, set your navBar to invisible with:

navController.navigationBar.translucent = true
navController.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
navController.navigationBar.shadowImage = UIImage()
navController.navigationBar.backgroundColor = UIColor.clearColor()

Create a view in storyboard or xib and make property in the VC, then add it with:

navController.view.insertSubview(navBarView, belowSubview: (navigationController?.navigationBar)!)

After that your subview should appear behind the bar buttons and it can work normally with your custom navBarView, but remember to remove that navBarView and return the navBar to default when view disappear:

navController.navigationBar.translucent     = false
navController.navigationBar.shadowImage     = nil
navController.navigationBar.setBackgroundImage(nil, forBarMetrics: .Default)
navController.navigationBar.backgroundColor = UIColor.whiteColor()
Comments