2015-04-06 96 views
1

我想在代碼中以編程方式更新約束。我已經將它們添加到故事板控制器中。我爲IBOutlet製作約束並連接它們。我在updateViewConstrains()增加值,但它不工作:如何以編程方式更新約束?

func updateViewConstraints() { 
    centerYConstraint.constant = 60 

    super.updateViewConstraints() 
} 
+0

顯示你的代碼,具體什麼不起作用? – Wain 2015-04-06 12:10:34

+0

覆蓋FUNC updateViewConstraints(){ centerYConstraint.constant = 60個 super.updateViewConstraints() } – Nik 2015-04-06 12:15:20

回答

1

您可以更新佈局約束的constant財產。

1

嘗試myConstraintOutlet.constant = newValue;

4

viewController.h文件中創建一個IBOutlet

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nameButtonVerticalConstraint; 

現在它與有關自動佈局約束連接:

enter image description here

現在,你可以簡單地改變約束像這樣:

self.nameButtonVerticalConstraint.constant=25; 

如果你想更平滑的過渡,你可以把它放在一個動畫塊內:

[UIView animateWithDuration:1.2 delay:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{ 
    self.nameButtonVerticalConstraint.constant=50; 
    [self.view layoutIfNeeded]; 
} completion:nil]; 

編輯:這裏是來自this文章

摘錄如果其他約束會因爲更新的影響根據上述約束,還必須調用以下內容:

[viewForUpdate setNeedsUpdateConstraints]; 

現在,通過調用動畫顯示視圖在您的動畫塊中嵌入layoutIfNeeded

+0

我嘗試相同的,但沒有工作:( – Nik 2015-04-06 12:51:39

+0

@Nik。編輯答案請檢查 – ShahiM 2015-04-07 06:09:35