iOS - 通过Swift更改约束的乘数 [英] iOS - Change the multiplier of constraint by Swift
本文介绍了iOS - 通过Swift更改约束的乘数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Swift更改约束的乘数。
How to change the multiplier of a constraint by using Swift.
someConstraint.multiplier = 0.6 // error: 'multiplier' is get-only property
我想知道如何更改代码中的乘数(Swift) 。
I would like to know how to change the multiplier in code (Swift).
推荐答案
由于乘数
是一个只读属性,你可以要改变它,你需要用它修改过的克隆来替换约束。
Since multiplier
is a read-only property and you can't change it, you need to replace the constraint with its modified clone.
你可以写一个扩展来做它,如:
You can write an extension to do it, like:
extension NSLayoutConstraint {
func constraintWithMultiplier(_ multiplier: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint.constraintWithItem(self.firstItem, attribute: self.firstAttribute, relatedBy: self.relation, toItem: self.secondItem, attribute: self.secondAttribute, multiplier: multiplier, constant: self.constant)
}
}
Swift 3.0+版本:
Swift 3.0+ version:
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)
}
}
用法:
var newConstraint = self.constraintToChange.constraintWithMultiplier(0.75)
self.view!.removeConstraint(self.constraintToChange)
self.view!.addConstraint(self.constraintToChange = newConstraint)
self.view!.layoutIfNeeded()
这篇关于iOS - 通过Swift更改约束的乘数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文