iosobjective-cuinavigationitem

Placement of navigation bar buttons


I am making an iPhone app and I have a UINavigationController as my root view and then UIVIewControllers from this. My Register button segues to the registration screen which automatically creates a Navigation Bar for me with the back button on the top left.

I have replaced the standard back button with my own image with the code below:

UIImage *backImage = [UIImage imageNamed:@"customBackButton.png"];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(0, 0, 100, 70);
[backButton setImage:backImage forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(popNavigationController:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton] ;
self.navigationItem.leftBarButtonItem = backBarButtonItem;

I have also added a rightBarButtonItem to test but my issue is however that both these buttons arent in the corners of the screen as can be seen here. enter image description here

Most other apps have the navigation bar buttons right in the corners as can be seen here from another app I found online as reference

enter image description here

I have tried to change the values here but that does nothing - the buttons stay where they are.

// Changing frames x-coordinate
backButton.frame = CGRectMake(-220, 0, 100, 70);

What do I need to do to set the buttons right in the corners of the navigation bar?

EDIT: If I use [backButton sizeToFit]; my image is displayed as below (the top grey bar is the navigation bar). Do I need to make the image the correct size?

enter image description here


Solution

  • If you want to change position of UIBarButtonItem you should use fake bar items as spacers

    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -10;
    

    Now you can set the array of bar items to achieve result needed

    self.navigationItem.leftBarButtonItems = @[negativeSpacer, backBarButtonItem];