2

I try to set UIBarButtonItem with different size images in the navigation bar. So I create a UIBarButtonItem based custom view and set the custom view's frame to constraint the UIBarButtonItem's width. It had been working well before I updated the software to iOS 11. That set custom view's frame to constraint the UIBarButtonItem's width seems no longer useful on iOS 11.

I used the image defaultImage with 120*120:

UIButton *leftCustomButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];

[leftCustomButton setImage:[UIImage imageNamed:@"defaultImage"] forState:UIControlStateNormal];

UIBarButtonItem * leftButtonItem =[[UIBarButtonItem alloc] initWithCustomView:leftCustomButton];

self.navigationItem.leftBarButtonItems = @[self.headerIconItem];

On iOS10, iOS9 the leftBarButtonItem's image is not stretched. It show's like:

show on iOS 10

But the leftBarButtonItem's image is stretched on iOS11. It show's in the picture below.

show on iOS 11

Is there have some ways to constraint UIBarButtonItem's width in the navigation bar on iOS 11?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Stoull
  • 1,098
  • 8
  • 13

2 Answers2

7

Starting with iOS 11 UIBarButtonItems are now laid out using the auto layout engine, in your case when targeting iOS 11 you should say something like:

UIButton *leftCustomButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];

[leftCustomButton.widthAnchor constraintEqualToConstant:35].active = YES;
[leftCustomButton.heightAnchor constraintEqualToConstant:35].active = YES; 

[leftCustomButton setImage:[UIImage imageNamed:@"defaultImage"] forState:UIControlStateNormal];
UIBarButtonItem * leftButtonItem =[[UIBarButtonItem alloc] initWithCustomView:leftCustomButton];
self.navigationItem.leftBarButtonItems = @[leftButtonItem];

For more information you should see the Updating Your App for iOS 11 WWDC 2017 session.

beyowulf
  • 15,101
  • 2
  • 34
  • 40
  • where does `headerIconItem` come from? Thanks – Morphing Coffee Apr 28 '18 at 22:49
  • @Evusas I think that's just an oversight from the original post. I edited the answer to make it clear that once you create the bar button item you should set that to your view controller's `navigationItem` as the desired left or right bar button item(s). – beyowulf Apr 29 '18 at 15:50
0

Applicable for Swift 5

let titleView = createTitleLabel() // Create UILabel view with specific settings
titleView.widthAnchor.constraint(equalToConstant: 165).isActive = true
let title = UIBarButtonItem(customView: titleView)