最好在更改约束之前或之后调用 .layoutIfNeeded()

Is best to call .layoutIfNeeded() before or after constraints are changed

我有一个按钮可以根据特定情况改变大小。我不需要完成动画,因为用户永远不会看到发生的变化。有时,当从较小尺寸切换回较大尺寸时,按钮会卡在较小尺寸处。我认为 layoutIfNeeded() 可以解决问题。

问题是我应该在下面的setCameraButtonToNormalSize()函数中什么时候调用layoutIfNeeded()

lazy var cameraButton: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.addTarget(self, action: #selector(cameraButtonPressed), for: .touchUpInside)
    return button
}()

let normalSize: CGFloat = 50
let smallerSize: CGFloat = 5

var cameraButtonWidthConstraint: NSLayoutConstraint?
var cameraButtonHeightConstraint: NSLayoutConstraint?

func setCameraButtonToNormalSize() {

    // before the constraints are changed

    cameraButtonWidthConstraint?.isActive = false
    cameraButtonHeightConstraint?.isActive = false

    cameraButtonWidthConstraint = cameraButton.widthAnchor.constraint(equalToConstant: normalSize)
    cameraButtonWidthConstraint?.isActive = true
    cameraButtonHeightConstraint = cameraButton.heightAnchor.constraint(equalToConstant: normalSize)
    cameraButtonHeightConstraint?.isActive = true

    // after the constraints are changed
}

fileprivate func setCameraButtonToSmallerSize() {

    cameraButtonWidthConstraint?.isActive = false
    cameraButtonHeightConstraint?.isActive = false

    cameraButtonWidthConstraint = cameraButton.widthAnchor.constraint(equalToConstant: smallerSize)
    cameraButtonWidthConstraint?.isActive = true
    cameraButtonHeightConstraint = cameraButton.heightAnchor.constraint(equalToConstant: smallerSize)
    cameraButtonHeightConstraint?.isActive = true
}

需要在

之后调用
// after the constraints are changed
 self.view.layoutIfNeeded()