Navigation items disappearing from UINavigationBar
I am adding a custom background image to my navbar creating an image view and executing [navigationController.navigationBar addSubview:imageView]
.
The background is fine. But as soon as I do that, my other navigation elements start to behave strangely. Sometimes it appears navigationItem.title
, the back button disappears. And this is completely coincidental. Any idea what could be causing this?
Thank.
source to share
As an additional thought, I was able to create a fully customizable navigation bar by overriding drawRect:
to display a background image. From there it was easy to set the properties leftBarButtonItem
, rightBarButtonItem
and titleView
properties of my nav controller navigationItem
to create custom buttons and titles. This works with inline nav controller / navbar / nav logic elements, so there is no danger of things (like bar buttons) getting hidden or obscured.
In category UINavigationBar
:
- ( void )drawRect:( CGRect )rect
{
[ [ UIImage imageNamed:@"background-image.png" ] drawInRect:CGRectMake( 0, 0,
self.frame.size.width, self.frame.size.height ) ];
}
Just before calling pushViewController:animated:
do the following:
UIButton * leftButton = [ UIButton buttonWithType:UIButtonTypeCustom ];
leftButton.frame = CGRectMake( 0.0, 0.0, 65.0, 32.0 );
[ leftButton setImage:[ UIImage imageNamed:@"left.png" ] forState:UIControlStateNormal ];
[ leftButton addTarget:self action:@selector( leftAction ) forControlEvents:UIControlEventTouchUpInside ];
UIButton * rightButton = [ UIButton buttonWithType:UIButtonTypeCustom ];
rightButton.frame = CGRectMake( 0.0, 0.0, 65.0, 32.0 );
[ rightButton setImage:[ UIImage imageNamed:@"right.png" ] forState:UIControlStateNormal ];
[ rightButton addTarget:self action:@selector( rightAction ) forControlEvents:UIControlEventTouchUpInside ];
UIImageView * titleView = [ [ UIImageView alloc ] initWithImage:[ UIImage imageNamed:@"title.png" ] ];
UIBarButtonItem * leftBarButtonItem = [ [ UIBarButtonItem alloc ] initWithCustomView :leftButton ];
UIBarButtonItem * rightBarButtonItem = [ [ UIBarButtonItem alloc ] initWithCustomView:rightButton ];
nextController.navigationItem.leftBarButtonItem = leftButtonItem;
nextController.navigationItem.rightBarButtonItem = rightButtonItem;
nextController.navigationItem.titleView = titleView;
It's a little busy, but you can abstract all this code into a method (or a series of it) somewhere else. This approach tends to work well if you want to completely override any style that appears in your navigation bar.
Hope this helps!
source to share