プログラムで高さ拘束を更新する
Update Height Constraint Programmatically
解決:
新しい制約を追加する代わりに、既存の制約の定数を変更する必要があります。
IBOutletを使用して、InterfaceBuilderの制約に接続します。
@property(非アトミック、弱い)NSLayoutConstraint * heightConstraint;次に、プログラムで設定する必要がある場合は、制約に定数プロパティを設定するだけです。
heightConstraint.constant = 100;また
Interface Builderでペン先にアクセスできない場合は、コードで制約を見つけてください。
NSLayoutConstraint * heightConstraint; for(NSLayoutConstraint * myView.constraintsの制約){if(constraint.firstAttribute == NSLayoutAttributeHeight){heightConstraint =制約;壊す; }} heightConstraint.constant = 100;そしてSwiftでは:
if letconstraint =(myView.constraints.filter {$ 0.firstAttribute == .width} .first){constraint.constant = 100.0}
高さ制約の参照を取得するには:制約で+ Ctrlをクリックし、クラスファイルにドラッグアンドドロップします。
制約値を更新するには:
self.heightConstraint.constant = 300; [self.view updateConstraints];
この迅速な拡張機能を使用するより柔軟な方法:
拡張UIView {func updateConstraint(attribute:NSLayoutAttribute、constant:CGFloat)-> Void {if letConstraint =(self.constraints.filter {$ 0.firstAttribute == attribute} .first){constraint.constant = constant self.layoutIfNeeded() }}}このビュー拡張を使用して、既存の制約の定数値を更新する方法:
//高さ定数を更新するtestView.updateConstraint(attribute:NSLayoutAttribute.height、constant:20.0)//幅定数を更新するtestView.updateConstraint(attribute:NSLayoutAttribute.width、constant:20.0)