最好在更改约束之前或之后调用 .layoutIfNeeded()
Posted
技术标签:
【中文标题】最好在更改约束之前或之后调用 .layoutIfNeeded()【英文标题】:Is best to call .layoutIfNeeded() before or after constraints are changed 【发布时间】:2020-01-11 16:32:29 【问题描述】:我有一个按钮,可以根据特定情况更改大小。我不需要完成动画,因为用户永远不会看到更改发生。有时,当从较小的尺寸切换回较大的尺寸时,按钮会卡在较小的尺寸上。我认为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
【问题讨论】:
【参考方案1】:你需要在之后调用它
// after the constraints are changed
self.view.layoutIfNeeded()
【讨论】:
以上是关于最好在更改约束之前或之后调用 .layoutIfNeeded()的主要内容,如果未能解决你的问题,请参考以下文章