在 Swift4 中,替换 navigationItem.leftBarButtonItem 会调整不需要的大小

in Swift4, replacement of navigationItem.leftBarButtonItem resizes unwanted

返回 VC 时,UIBarButtonItem 调整大小有问题,框架和图像的值不同。

var selectedR = 1
var leftFrame = CGRect()
var leftImage = UIImage()

override func viewDidLoad() {
    super.viewDidLoad()

    if selectedR == 0
    {
        leftFrame = CGRect(x: 0, y: 0, width: 33, height: 33)
        leftImage = UIImage(named: “pic-0”)!
    }
    else if selectedR == 1
    {
        leftFrame = CGRect(x: 0, y: 0, width: 79, height: 33)
        leftImage = UIImage(named: "pic-1")!
    }
    else if selectedR == 2
    {
        leftFrame =  CGRect(x: 0, y: 0, width: 34, height: 33)
        leftImage = UIImage(named: "pic-2”)!
    }

    let cButton = UIButton(frame: leftFrame)
    cButton.setImage(leftImage, for: UIControlState())
    cButton.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside)
    cButton.contentMode = UIViewContentMode.scaleAspectFit
    let leftItem = UIBarButtonItem(customView: cButton)
    self.navigationItem.leftBarButtonItem = leftItem
}

第一次选择的完美尺码 R = 1

使用不同的 selectedR 值返回到 viewDidLoad 时,图像会爆炸、扭曲并且设置 leftFrame 大小不被接受。

这一切在 swift 3 中都很完美,但在 swift 4 中却无处不在。任何帮助或建议将不胜感激。

iOS 10 和 11 之间的一个主要变化是现在栏按钮项目由自动布局引擎布局。通常这应该是向后兼容的。但是,如果您在布置栏按钮项目时遇到问题,您应该尝试设置约束,看看是否能解决您的问题。

在你的情况下你会说:

var selectedR = 1
var leftFrame = CGRect()
var leftImage = UIImage()

override func viewDidLoad() {
    super.viewDidLoad()

    if selectedR == 0
    {
        leftFrame = CGRect(x: 0, y: 0, width: 33, height: 33)
        leftImage = UIImage(named: “pic-0”)!
    }
    else if selectedR == 1
    {
        leftFrame = CGRect(x: 0, y: 0, width: 79, height: 33)
        leftImage = UIImage(named: "pic-1")!
    }
    else if selectedR == 2
    {
        leftFrame =  CGRect(x: 0, y: 0, width: 34, height: 33)
        leftImage = UIImage(named: "pic-2”)!
    }

    let cButton = UIButton(frame: leftFrame)
    cButton.widthAnchor.constraint(equalToConstant: leftFrame.width).isActive = true
    cButton.heightAnchor.constraint(equalToConstant: leftFrame.height).isActive = true
    cButton.setImage(leftImage, for: UIControlState())
    cButton.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside)
    cButton.contentMode = UIViewContentMode.scaleAspectFit
    let leftItem = UIBarButtonItem(customView: cButton)
    self.navigationItem.leftBarButtonItem = leftItem
}

Apple 的 WWDC 2017 对此进行了介绍sessionUpdating Your App for iOS 11