On iOS11, how to have UIToolbar to size all items to fit?
Asked Answered
A

1

8

Up to iOS 10, an UIToolbar with flexible space bar buttom items between its items would automatically reduce the font so that all text get displayed on the screen. Sample below (iOS 10):

iOS 10 Sample

Ever since XCode 9, when running iOS 11 on simulator my toolbar is displayed like this:

iOS 11 Sample

Not only did the text not have its font size reduced but the last bar button item (which has no text, only an image) is gone.

Trying to solve this, I've found out that since iOS 11, UIToolbar now uses Autolayout instead of Frames. Some posts related in a way with this problem suggests creating constraints for the items, specifying width and/or height for items.

However, what I want to achieve is fit everything in the toolbar, even if it means reducing the font size. I don't think I can go with setting fixed width/height programmatically then.

Also, this was built using IB on a Storyboard. UIBarButton class doesn't give me access to the UILabel (for text items) or ImageView (for items with image). I've inspected and customView is nil at runtime.

I tried creating the items via code, setting customView to an UILabel with adjustsFontSizeToFitWidth set to true without any luck. I have no clue what is the purpose of flexible space bar items on iOS 11.

So, how to mimic the behavior I had before? Fit all items and resize text automatically?

Albumin answered 25/10, 2017 at 17:52 Comment(3)
If you feel that valuable functionality has been lost, file a bug report with Apple.Hsiuhsu
@Hsiuhsu I could, yes. I just assumed I'm doing something wrong.Albumin
Every major update they loses something...Nofretete
M
0

You will need to manually set the size of the UIBarButtonItems, for example:

NSUInteger smallFontSize = SMALL_FONT;  // e.g. font size of 12
self.smallFont = [UIFont boldSystemFontOfSize:smallFontSize];
self.smallFontAttributes = @{NSFontAttributeName: self.smallFont};

- (void)shrinkButtonFontSize:(NSArray *)barButtonItems {
 for (UIBarButtonItem* button in barButtonItems) {
    [button setTitleTextAttributes:self.smallFontAttributes forState:UIControlStateNormal];
    [button setTitleTextAttributes:self.smallFontAttributes forState:UIControlStateSelected];
    [button setTitleTextAttributes:self.smallFontAttributes forState:UIControlStateDisabled];
 }
}
Margueritamarguerite answered 4/11, 2017 at 17:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.