7

I notice the blank space between bar button items is quite large. I want to reduce the space to have more room for my title. I tried to create fixed space then added it among the buttons but it didn't work. Does anybody know how to do it?

UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixedItem.width = 10.0f;
self.navigationItem.rightBarButtonItems = @[settingsButtonItem, fixedItem, speakerButtonItem, fixedItem, favouriteButtonItem];
LongNV
  • 892
  • 9
  • 21

2 Answers2

1

You're close but what you need is a negative fixed space. If your other UIBarButtonItems use custom views, check your frame for those views. Here's an example of adding two right bar button items that hug the edge more. In your case you'll want to add negative space between the buttons as well.

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

UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(0, 0, 44, 44);
[backButton setImage:[[UIImage imageNamed:@"ic_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]
            forState:UIControlStateNormal];
backButton.imageView.tintColor = [UIColor whiteColor];
[backButton addTarget:self
               action:@selector(backPressed)
     forControlEvents:UIControlEventTouchUpInside];

self.backNavButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
self.backNavButton.enabled = NO;

UIButton *forwardButton = [UIButton buttonWithType:UIButtonTypeCustom];
forwardButton.frame = CGRectMake(0, 0, 44, 44);
[forwardButton setImage:[forwardImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]
               forState:UIControlStateNormal];
forwardButton.imageView.tintColor = [UIColor whiteColor];
[forwardButton addTarget:self
                  action:@selector(forwardPressed)
        forControlEvents:UIControlEventTouchUpInside];

self.forwardNavButton = [[UIBarButtonItem alloc] initWithCustomView:forwardButton];
self.forwardNavButton.enabled = NO;

self.navigationItem.rightBarButtonItems = @[negativeSpace,self.forwardNavButton,self.backNavButton];
NRimer
  • 284
  • 1
  • 3
  • Thank you so much! The trick was to first set UIButtons with their frames, and only then set the corresponding UIBarButtons. I had been struggling so much with this. – Georges Oct 27 '15 at 03:32
1

Using Xcode 6.4, This worked beautifully for me with 1 line of code!
https://stackoverflow.com/a/26469607/3634990

self.myBarButtonItem.imageInsets = UIEdgeInsetsMake(0, 25, 0, -25);

Note- Unfortunately this does not move the hit area of the button, only its image. But a good solution if you just need to move the button a little bit!

Community
  • 1
  • 1
jungledev
  • 4,195
  • 1
  • 37
  • 52