Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does adding imageview to navigation bar in storyboard remove navbar?

I have a working app which is a tabbarcontroller based app. The first viewcontroller is a uitableviewcontroller. All 3 tabs have a navigation bar on the top, that I added from the object library. This is what the app looks like:

Original UITableViewController in first tab with UINavbar

Then I wanted to set the image on the navbar as a centered logo. So I looked around SO and found code that looks like this:

 UIImage *image = [UIImage imageNamed:@"icon57.png"];
 UIImageView *imageView = [[UIImageView alloc] initWithImage: image];
 self.navigationItem.titleView = imageView;

or

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"icon57.png"] forBarMetrics:UIBarMetricsDefault];

But it didnt work. I just got an empty white nav bar. So I decided to add a UIImageView to the navbar by dragging it in from the object library but for some reason it makes the navbar disappear and I end up with this:

After adding UIImageView to UINavBar

Why does this happen?

like image 855
marciokoko Avatar asked Aug 07 '13 16:08

marciokoko


1 Answers

The way you are doing it is not supported in Interface Builder. I would encourage you to file a radar to support doing that. You can accomplish this via two different ways, one in code, the other in IB.

Through Interface Builder

You can drag a UIView instance from the object library and drop it into the center of the nav bar. This will set the view inside the title area of the bar. You may then take a UIImageView instance and add it as a subview of that the view you just added.

Through Code

You can set the UIImageView through code, using the titleView property of your view controller's navigation item:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIImage *logo = [UIImage imageNamed:@"logo.png"];
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:logo];
}

EDIT:

In order to set it on the left side, you'll have to wrap the image view in a UIBarButtonItem. You can do that in IB using the same procedure described above, or in code like the following:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIImage *logo = [UIImage imageNamed:@"logo.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:logo];    
    UIBarButtonItem *imageButton = [[UIBarButtonItem alloc] initWithCustomView:imageView];

    self.navigationItem.leftBarButtonItem = imageButton;
}
like image 187
Wayne Hartman Avatar answered Nov 06 '22 12:11

Wayne Hartman