切换到 Swift 4 后 BarButtonItem 格式错误

BarButtonItem malformed after switch to Swift 4

升级到Swift4后,我用来添加自定义的代码UIBarButtonItem不再有效,而是以一种特殊的方式压缩图像:

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

看来框架是正确的,在控制台中我收到以下控制台消息:

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

有什么想法吗?谢谢大家!

这是当前 iOS 11 版本的一个已知错误。 UIBarButton 项目现在使用约束而不是早期的框架方法。

关注 and 以获得解决方案或更多解释。

并且 帮助新的实施。