iOS engineer who likes clean, simple designs and sans-serif.

Loading

Re-position UIBarButtonItem

If you’ve ever tried to re-position a UIBarButtonItem, you’ll know that it’s kind of a pain. This was the best way I could think of to do it.

First, create a UIButton.

// Layout Close Button
UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
closeButton.frame = CGRectMake(0,0,30,30);
[closeButton setBackgroundImage:[UIImage imageNamed:@"x_circle"] forState:UIControlStateNormal];
[closeButton setBackgroundImage:[UIImage imageNamed:@"x_circle_highlighted"] forState:UIControlStateHighlighted];
[closeButton addTarget:self action:@selector(handleCloseButtonTapped) forControlEvents:UIControlEventTouchUpInside];

Then, create a container UIView and add the UIButton to the UIView. This is also where you would re-position the button.

CGFloat closeButtonOffsetX = (SCREEN_WIDTH <= 375.0) ? 7 : 11;
CGFloat closeButtonOffsetY = (SCREEN_WIDTH <= 375.0) ? 1 : 1;
UIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
backButtonView.bounds = CGRectMake(backButtonView.frame.origin.x+closeButtonOffsetX,
                                   backButtonView.frame.origin.y+closeButtonOffsetY,
                                   backButtonView.frame.size.width,
                                   backButtonView.frame.size.height);
[backButtonView addSubview:closeButton];

Now, create the UIBarButtonItem with a view.

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];

Leave a Comment