navigation bar rightbaritem image-button bug iOS 11
Thanks all for contributing! you guys are right!. for xcode9 ios11 you need to put a constraint.
let widthConstraint = button.widthAnchor.constraint(equalToConstant: 32)
let heightConstraint = button.heightAnchor.constraint(equalToConstant: 32)
heightConstraint.isActive = true
widthConstraint.isActive = true
Reason
The problem appears because from ios 11 UIBarButtonItem
uses autolayout instead of dealing with frames.
Solution
You should add width constraint for this image-button if you use Xcode 9.
button.widthAnchor.constraint(equalToConstant: 32.0).isActive = true
button.heightAnchor.constraint(equalToConstant: 32.0).isActive = true
PS
button
is not UIBarButtonItem
, it is UIButton
inside UIBarButtonItem
. You should set constraint not for UIBarButtonItem
, but for elements inside it.
Well, The new barButtonItem
uses autolayout instead of dealing with frames.
The image you were adding to the button is larger than the button size itself. That's why the button itself got stretched to the image's size. You have to resize the image to match the needed button's size, before adding it to the button.
Objective C code is obsolete now. But for the user who has to build/maintain Objective C projects in iOS 11 has following translation from Swift ( Karoly Nyisztor answer ) to Objective C helpful.
// UIView+Navbar.h
#import <UIKit/UIKit.h>
@interface UIView (Navbar)
- (void)applyNavBarConstraints:(CGFloat)width height:(CGFloat)height;
@end
//----------
// UIView+Navbar.m
#import "UIView+Navbar.h"
@implementation UIView (Navbar)
- (void)applyNavBarConstraints:(CGFloat)width height:(CGFloat)height
{
if (width == 0 || height == 0) {
return;
}
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:height];
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:width];
[heightConstraint setActive:TRUE];
[widthConstraint setActive:TRUE];
}
//----------
// Usage :-
[button applyNavBarConstraints:33 height:33];