简体   繁体   中英

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:

在此处输入图片说明

  // 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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM