0

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

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

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

1 回答 1

0

你需要在之后调用它

// after the constraints are changed
 self.view.layoutIfNeeded()
于 2020-01-11T16:35:43.230 回答