Jason
Jason

Reputation: 650

Why is my title showing as a left button?

I have a navigationBar in my TabBarView. I want a rightBarButtonItem and a title on my navigationBar. Why is this happening? My code is in the viewDidLoad method. Why is my title showing as a left button item? Then when I click on it, it acts like it's moving a view then my right bar button item is gone and the title is correct.

UINavigationBar *myNavBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320,40)];
myNavBar.barStyle = UIBarStyleBlackOpaque;

[self.view addSubview:myNavBar];

//Creates the title.
UINavigationItem *title = [[UINavigationItem alloc] initWithTitle:@"My Title"];

[myNavBar pushNavigationItem:title animated:NO];

//Creates the button.
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self
action:@selector(showMail:)];

UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:nil];
navItem.rightBarButtonItem = button;

// add the UINavigationItem to the navigation bar
[myNavBar pushNavigationItem:navItem animated:NO];

Upvotes: 1

Views: 199

Answers (2)

user
user

Reputation: 11

You are creating multiple navigation buttons. You should set all those properties to a single button. If you want to set title for bar, you can set it as self.title = @"title";

You can also try to set navigationbar.titleview.

Upvotes: 0

Tommy Devoy
Tommy Devoy

Reputation: 13549

UINavigationItem contains the title and bar button items. You're creating multiple navigationItems, while instead you should just be assigning the properties of a single UINavigationItem.

Take a look of the header file and you'll see it contains everything you need:

NS_CLASS_AVAILABLE_IOS(2_0) @interface UINavigationItem : NSObject <NSCoding> {
 @private
    NSString        *_title;
    NSString        *_backButtonTitle;
    UIBarButtonItem *_backBarButtonItem;
    NSString        *_prompt;
    NSInteger        _tag;
    id               _context;
    UINavigationBar *_navigationBar;
    UIView          *_defaultTitleView;
    UIView          *_titleView;
    UIView          *_backButtonView;
    NSArray         *_leftBarButtonItems;
    NSArray         *_rightBarButtonItems;
    NSArray         *_customLeftViews;
    NSArray         *_customRightViews;
    BOOL             _hidesBackButton;
    BOOL             _leftItemsSupplementBackButton;
    UIImageView     *_frozenTitleView;
}

Just assign a single instance of it. You shouldn't be allocating multiple UINavigationItems.

Upvotes: 4

Related Questions