iOS - 通过 Swift 更改约束的乘数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37294522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:05:27  来源:igfitidea点击:

iOS - Change the multiplier of constraint by Swift

iosswift

提问by ryo

How to change the multiplier of a constraint by using Swift.

如何使用 Swift 更改约束的乘数。

someConstraint.multiplier = 0.6 // error: 'multiplier' is get-only property

I would like to know how to change the multiplier in code (Swift).

我想知道如何更改代码(Swift)中的乘数。

回答by KlimczakM

Since multiplieris a read-only property and you can't change it, you need to replace the constraint with its modified clone.

由于multiplier是只读属性并且您无法更改它,因此您需要将约束替换为其修改后的克隆。

You can use an extension to do it, like this:

您可以使用扩展来执行此操作,如下所示:

Swift 4/5:

斯威夫特 4/5

extension NSLayoutConstraint {
    func constraintWithMultiplier(_ multiplier: CGFloat) -> NSLayoutConstraint {
        return NSLayoutConstraint(item: self.firstItem!, attribute: self.firstAttribute, relatedBy: self.relation, toItem: self.secondItem, attribute: self.secondAttribute, multiplier: multiplier, constant: self.constant)
    }
}

Usage:

用法:

let newConstraint = constraintToChange.constraintWithMultiplier(0.75)
view.removeConstraint(constraintToChange)
view.addConstraint(newConstraint)
view.layoutIfNeeded()
constraintToChange = newConstraint