在没有 IBOutlets 的情况下以编程方式更新布局约束 - Swift
Update layout constraints programmatically without IBOutlets - Swift
我正在尝试通过在点击 "open" 按钮时更改左锚点约束来创建滑出菜单。我见过有人在约束上使用 IBOutlets 来做到这一点,但我正在使用的视图完全以编程方式制作,阻止我这样做。
视图最初位于屏幕外,所以我想我可以在点击 "open" 按钮时更改约束,但下面的代码什么也没做。
@objc func slideMenu() {
sideMenu.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
view.setNeedsUpdateConstraints()
}
有没有办法在没有 IBOutlet 的情况下更新左锚点约束?
将约束存储在变量中,更改 常量并调用layoutIfNeeded
当你需要动画时。
// Declare this along with the other variables in your class
var constraintVariable: NSLayoutConstraint!
.
.
.
// Where you set your constraints. Store the constraint to be animated in the variable and make it active
// Your other constraints
constraintVariable = sideMenu.leftAnchor.constraint(equalTo: view.leftAnchor, constant: someNegativeValue);
constraintVariable.isActive = true
.
.
.
@objc func slideMenu() {
UIView.animate(withDuration: suitableDuration) {
constraintVariable.constant = requiredValue
view.setNeedsLayout()
view.layoutIfNeeded()
}
}
我正在尝试通过在点击 "open" 按钮时更改左锚点约束来创建滑出菜单。我见过有人在约束上使用 IBOutlets 来做到这一点,但我正在使用的视图完全以编程方式制作,阻止我这样做。
视图最初位于屏幕外,所以我想我可以在点击 "open" 按钮时更改约束,但下面的代码什么也没做。
@objc func slideMenu() {
sideMenu.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
view.setNeedsUpdateConstraints()
}
有没有办法在没有 IBOutlet 的情况下更新左锚点约束?
将约束存储在变量中,更改 常量并调用layoutIfNeeded
当你需要动画时。
// Declare this along with the other variables in your class
var constraintVariable: NSLayoutConstraint!
.
.
.
// Where you set your constraints. Store the constraint to be animated in the variable and make it active
// Your other constraints
constraintVariable = sideMenu.leftAnchor.constraint(equalTo: view.leftAnchor, constant: someNegativeValue);
constraintVariable.isActive = true
.
.
.
@objc func slideMenu() {
UIView.animate(withDuration: suitableDuration) {
constraintVariable.constant = requiredValue
view.setNeedsLayout()
view.layoutIfNeeded()
}
}