Search code examples
iphoneiosobjective-cuinavigationcontrollerback-button

How do I change the location of the back button on iOS?


You see I am making a completely custom navigation bar and when i create the back button it doesn't stay in the right place as you can see below the code.

here is my code for the app

- (void)viewDidLoad
{
    [super viewDidLoad];
    if(self.navigationController.viewControllers.count > 1) {
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [backButton setTitle:@"" forState:UIControlStateNormal];
    [backButton setBackgroundImage:[UIImage imageNamed:@"backButton.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(didTapBackButton:) forControlEvents:UIControlEventTouchUpInside];
    backButton.frame = CGRectMake(0.0f, 0.0f, 44.0f, 45.0f);
    UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = backButtonItem;
}

}

Pic


Solution

  • I think you can just modify contentEdgeInsets to make the position of the button.

    Something like this:

    [backButton setContentEdgeInsets:UIEdgeInsetsMake(5, 0, -5, 0)];

    Come from UIButton Class Reference

    contentEdgeInsets

    The inset or outset margins for the rectangle surrounding all of the button’s content.

    @property(nonatomic) UIEdgeInsets contentEdgeInsets

    DiscussionUse this property to resize and reposition the effective drawing rectangle for the button content. The content comprises the button image and button title. You can specify a different value for each of the four insets (top, left, bottom, right). A positive value shrinks, or insets, that edge—moving it closer to the center of the button. A negative value expands, or outsets, that edge. Use the UIEdgeInsetsMake function to construct a value for this property. The default value is UIEdgeInsetsZero.