Dane Jordan Dane Jordan - 3 years ago 372
Swift Question

BarButtonItem malformed after switch to Swift 4

After upgrading to Swift 4, the code I used to add a custom

UIBarButtonItem
no longer works, and instead, squeezes the image in a peculiar fashion:

enter image description here

// In viewDidLayoutSubviews
if let backButton = Utils.createBackButton(color: .white, target: self, selector: #selector(LoginViewController.backPressed)) {
navigationItem.leftBarButtonItem = backButton
print("navigation button width", backButton)
}

// In Utils.swift
class func createBackButton(color: BackArrowColors, target: UIViewController, selector: Selector) -> UIBarButtonItem? {
var backImage = UIImage()
if color == .white {
backImage = UIImage(named: "back-arrow-white.png")!
} else if color == .black {
backImage = UIImage(named: "back-arrow-black.png")!
} else {
return nil
}

let backButton: UIButton = UIButton(type: UIButtonType.custom)
backButton.frame = CGRect(x: 0, y: 0, width: 35, height: 35)
backButton.contentMode = UIViewContentMode.scaleAspectFit
backButton.setImage(backImage, for: .normal)
backButton.addTarget(target, action: selector, for: .touchUpInside)
backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10)
let leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: backButton)
return leftBarButtonItem
}


It seems the frame is correct, in the console I get the following console message:

navigation button width <UIBarButtonItem: 0x7fb3d7c0d010> view=<UIButton: 0x7fb3d7c20ae0; frame = (0 0; 35 35); opaque = NO; layer = <CALayer: 0x60c000238b40>>


Any ideas? Thanks guys!

Answer Source

This is a known bug with current iOS 11 release. UIBarButton items now uses constraints instead of the earlier frame approach.

Follow this and this for solution or more explanation.

And this link helps with the new implementation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download