Search code examples
iosuinavigationbaruitoolbar

UIBarButtonItem with UIImage too wide


I have a UINavigationBar and a UIToolbar (in separate views) which contain buttons and flexible space. The UIBarButtonItems' background is set like this:

bgImage = [[UIImage imageNamed:@"MyBackgroundImage.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 5)];
[self setBackgroundImage:bgImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

Within the UINavigationBar, the items look just fine, optimal size and all.

BUT, within the UIToolbar, the items are always stretched to at least the width of bgImage (100 points in this case):

enter image description here enter image description here

Any ideas why, or how to solve that? Please tell me if you need more info.


Solution

  • This appears to be a bug in UIToolbar. I gave it a try and the only "fix" that worked for me was to manually set the width of the UIBarButtonItem:

    barButtonItem.width = 40f;
    

    This will work fine for buttons with images, but not for text buttons as the size of the text may vary due to localization.