Domanda

I'am trying to add UIButtonBarItem programmatically to UINavigationBar. I have this class Topbar, that a import on some of my ViewControllers, and then invoke by: [self.view addSubview:[Topbar insertTopbar]];

#import "Topbar.h"

@implementation Topbar

+(UINavigationBar*)insertTopbar
{
    UINavigationBar *navBar = [ [UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

    UINavigationItem *navTitle = [UINavigationItem alloc];
    navTitle.title = @"MyApp";

    UINavigationItem *navAdd = [UINavigationItem alloc];
    navAdd.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd target:self action:@selector(addFood)];

    [navBar setItems:@[navAdd, navTitle] animated:false];
    return navBar;
}

@end

But when i try to set the items using navBar setItems:@[navAdd, navTitle] it ads a "Back"-button enter image description here

If i then leave out navTitleso it reads navBar setItems:@[navAdd], the "+"-sign suddenly appears. It seems like that the "navTitle" pushes into the first item. enter image description here

È stato utile?

Soluzione

Try out the following method, did some tweeks and is working fine for me now! :)

enter image description here

-(UINavigationBar*)insertTopbar
{
UINavigationBar *navBar = [ [UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UINavigationItem *navAdd = [UINavigationItem alloc];
navAdd.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd target:self action:@selector(addFood)];
[navBar pushNavigationItem:navAdd animated:YES];
navBar.topItem.title = @"MyApp";
return navBar;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top