2016-05-18 11 views
8

Swiftを使用して制約の乗数を変更する方法。iOS - Swiftによる制約の乗数の変更

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

コード内の乗数(Swift)を変更する方法を知りたいと思います。

+2

と適切なタイミングで正しいものを有効/無効にします。 – luk2302

+8

http://stackoverflow.com/questions/19593641/can-i-change-multiplier-property-for-nslayoutconstraint –

答えて

30

multiplierは読み取り専用プロパティであり、変更することはできません。その制約を変更されたクローンで置き換える必要があります。

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

スウィフト3.0+バージョン:

使用法:

あなたのような、それを行うための拡張機能を記述することができます別の乗算器と、複数の制約を作成

var newConstraint = self.constraintToChange.constraintWithMultiplier(0.75) 
self.view!.removeConstraint(self.constraintToChange) 
self.view!.addConstraint(self.constraintToChange = newConstraint) 
self.view!.layoutIfNeeded() 
+1

ありがとうございました。私はあなたのコードをしようとします。しかし、私は自分が望むものを達成することができません。なぜなら、「self.view!」のためです。私は 'self.view! 'を私の場合に固定しました。しかし、私はAndrew Schreiberの方法を既存の「NSLayoutConstraintの乗数プロパティを変更できますか?」で使用します。それはうまくいった。私はそれをもっと探す必要があった。 – redstone

関連する問題