1
votes

I've noticed that iOS 11 has made some change to the UIBarButtonItem. After solving the sizing problem of the image of UIBarButtonItem, I find myself facing another even more strange issue.

We have a UIToolBar with several UIBarButtonItems and we used to set the width of the UIBarButtonItem as 40 and the width of the UIButton.image as 24, which leaves a nice spacing between every two UIBarButtonItems. However, in iOS 11, the space disappear.

I tried with

[self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 24));
    }];

NSLayoutConstraint *w = [self.deleteButton.imageView.widthAnchor constraintEqualToConstant:24];
NSLayoutConstraint *h = [self.deleteButton.imageView.widthAnchor constraintEqualToConstant:24];
w.active = YES;
h.active = YES;

but it doesn't work as I thought.

I either get a list of stretched images with CGSize(40, 24) or a list of UIBarButtonItem with CGSize(24, 24) lining up in the UINavigationBar one by one without spacing.

Are there anything other constraints I need to add to create the spacing?

2

2 Answers

1
votes

Try this:

UIButton*(^buttonWith)(NSString *) = ^(NSString *imageName) {
    CGFloat size = 40.0;
    UIButton *button = [[UIButton alloc] initWithFrame: CGRectMake(0.0, 0.0, size, size)];
    [button setImage: [[UIImage imageNamed: imageName] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal]  forState: UIControlStateNormal];
    [button addConstraint: [NSLayoutConstraint constraintWithItem: button attribute: NSLayoutAttributeWidth relatedBy: NSLayoutRelationEqual toItem: nil attribute: NSLayoutAttributeNotAnAttribute multiplier: 1.0 constant: size]];
    [button addConstraint: [NSLayoutConstraint constraintWithItem: button attribute: NSLayoutAttributeHeight relatedBy: NSLayoutRelationEqual toItem: nil attribute: NSLayoutAttributeNotAnAttribute multiplier: 1.0 constant: size]];
    return button;
};

Usage:

UIButton *resetButton = buttonWith(@"reset");
self.resetBarButton = [[UIBarButtonItem alloc] initWithCustomView: resetButton];

UIButton *backButton = buttonWith(@"back");
self.backBarButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];

self.navigationItem.leftBarButtonItems = @[self.backBarButton, self.resetBarButton];
0
votes

In storyboard you can place another UIBarButtonItem in between the buttons that need spacing. set the text to spaces only. see screen shots.

enter image description here

enter image description here

enter image description here