问题
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:
But the leftBarButtonItem's image is stretched on iOS11. It show's in the picture below.
Is there have some ways to constraint UIBarButtonItem's width in the navigation bar on iOS 11?
回答1:
Starting with iOS 11 UIBarButtonItem
s 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.
来源:https://stackoverflow.com/questions/46363375/constraint-a-uibarbuttonitems-size-in-the-navigaiton-bar-with-ios-11