2016-04-19 5 views
0

私は自分のコードにいくつかのボタンのレイアウトを調整する機能を持っています。これは、.hiddenが設定されているときに呼び出されます。プログラムで制約を調整するには、まずそれらを削除してから再追加する必要がありますか?

private func layoutButtons() { 

     redButton.hidden = !redButtonEnabled 
     redButtonLabel.hidden = !redButtonEnabled 
     yellowButton.hidden = !yellowButtonEnabled 
     yellowButtonLabel.hidden = !yellowButtonEnabled 

     removeConstraint(yellowButtonTrailingContraint) 
     if yellowButtonEnabled && !redButtonEnabled { 
      yellowButtonTrailingContraint = NSLayoutConstraint(item: yellowButton, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: -horizontalMargin) 
     } else { 
      yellowButtonTrailingContraint = NSLayoutConstraint(item: yellowButton, attribute: .Trailing, relatedBy: .Equal, toItem: redButton, attribute: .Leading, multiplier: 1.0, constant: -horizontalMargin) 
     } 
     addConstraint(yellowButtonTrailingContraint) 
    } 

制約を変更する前に削除してから、上記のように後で再追加する必要がありますか?どこかの例でこれを見たが、ちょっと変わっているようだ。これについての指針は本当に感謝しています。ありがとう!

答えて

3

はい、制約を削除することは可能ですが、必ずしも必要ではありません。

レイアウトを更新する定数値を変更して制約を編集することがあります。たとえば :

var constraintHeight = NSLayoutConstraint(item: someView, attribute: .Height, relatedBy:.Equal, toItem:nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100) 
    someView.addConstraint(constraintHeight) 
    ... 
    //The Constraint can be edited later by changing the constant value 
    constraintHeight.constant = 200 
    someView.layoutIfNeeded() 

たり、有効または例えば、それらを無効にすることができます

var constraintHeight1 = NSLayoutConstraint(item: someView, attribute: .Height, relatedBy:.Equal, toItem:nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100) 
    var constraintHeight2 = NSLayoutConstraint(item: someView, attribute: .Height, relatedBy:.Equal, toItem:nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 200) 
    constraintHeight1.active = true 
    constraintHeight2.active = false 

    someView.addConstraint(constraintHeight1) 
    someView.addConstraint(constraintHeight2) 

    ... 
    //Later you can set the other constraint as active 
    constraintHeight1.active = false 
    constraintHeight2.active = true 
    someView.layoutIfNeeded() 

任意の時点でのみアクティブな制約は、ビューの最終的なレイアウトを決定するために使用されます。したがって、いくつかの選択肢がありますが、競合する2つの制約が決してアクティブでないことを確認する必要があります。そうしないと、アプリケーションがクラッシュします。競合する制約の1つを削除するか、無効にする必要があります。希望する:]

+0

あなたの答えをありがとう!私を助けてくれました。上記の私の例は、削除して再度追加する必要はありませんか?もちろん、layoutIfNeededを呼び出すだけで十分です。 – Kex

+1

実行時に@Kex制約を削除するとほとんどの場合パフォーマンスが低下するため、お勧めしません。無効化または単純に一定値(または乗数)を変更することが最初に行われるべきです。 – slxl

関連する問題