Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optionally set navigationbar background image

I have the need to draw a background image or set a tint color on a navigation bar, but I also need the option to have the navigation bar appear as it normally would. I'm currently using a category to support If my app does not specify a background image, what can I do instead to ensure the drawRect method does it normally would do?

I.E. -

@implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
    if(hasImage){
        UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://myimageurl.com/img.jpg"]]];
        [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    }else{
        ??????
    }
}
@end
like image 337
E-Madd Avatar asked Jan 26 '26 15:01

E-Madd


1 Answers

I actually ended up doing something entirely different and I'm wondering why nobody hasn't discovered this before. One of the approaches I've seen in the course of my Googling on the subject was simply adding an image as a subview to the UINavigationBar. The only problem was this made the buttons in the bar not clickable. The fix was to disable user interaction on the image.

myUIImageView.userInteractionEnabled = NO; [myNavController.navigationBar addSubview:myUIImageView]; [myNavController.navigationBar sendSubviewToBack:myUIImageView];

With that, everything looks/works great and I don't have to override the drawRect method with a category, swizzle methods or any of that funky stuff. Simple and clean.

like image 200
E-Madd Avatar answered Jan 29 '26 06:01

E-Madd