Search code examples
iosobjective-cuinavigationbaruibarbuttonitemuibaritem

Get rid of the space on the right side of a UINavigationBar


So, this is what I'm trying to accomplish:

That's how it should look

It's a UINavigationBar with a UIBarButtonItem that gets initialized with a custom UIButton.
Basically like this:

UIButton *favoriteButton = [UIButton buttonWithType:UIButtonTypeCustom];
[favoriteButton addTarget:target
                   action:action
         forControlEvents:UIControlEventTouchUpInside];
favoriteButton.frame = CGRectMake(0.0f, 0.0f, 44.0f, 44.0f);

UIImage *backgroundImage = [[UIImage imageNamed:@"favorite-button-background-orange"]
                    resizableImageWithCapInsets:UIEdgeInsetsMake(0, 2, 0, 0)];
[favoriteButton setBackgroundImage:backgroundImage
                          forState:UIControlStateNormal];

UIBarButtonItem *favoriteButtonItem = [[UIBarButtonItem alloc] initWithCustomView:favoriteButton];

The problem is I can't seem to get rid of that nasty little border on the right hand side of the UINavigationBar.

That's how it looks

I tried setting a custom TitleView as described in "How to remove padding next to a UIBarButtonItem" but this didn't change a thing.

I also tried adding another UIBarButtonItem with a negative width (as suggested in some blogposts I read) but that didn't help either.

UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                 target:nil
                 action:nil];
negativeSpacer.width = -5.0f;
self.navigationItem.rightBarButtonItems = %[favoriteButtonItem, negativeSpacer];

I assume iOS won't let me change it because the "rounded border" reserves some (unavoidable?) space / padding? So my question is. How should I work around this limitation? Do I need to create a custom UINavigationBar class? Can I fake it somehow by modifying the UIBarButtonItem? Am I just using the wrong component?


Solution

  • There would be two solutions. (It may not be exact solution)

    1) You should subclass UINavigationBar and play around with it. For example you may have to draw your UIBarButtonItem yourself in the right corner.

    2) Instead of using UINavigationBar, Use UIView and add subviews to make it exactly look like the UINavigationBar and use it.

    I hope second solution would be easy to achieve in your requirement. I don't think there would be any other way to achieve your requirement.