Constraint a UIBarButtonItem's size in the navigaiton bar with iOS 11

北城以北 提交于 2019-12-09 22:50:10

问题


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 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.



来源:https://stackoverflow.com/questions/46363375/constraint-a-uibarbuttonitems-size-in-the-navigaiton-bar-with-ios-11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!