2016-11-04 48 views
1

我在Storyboard中有4個按鈕,包含BottomSpace和Horizo​​ntal Alignment約束。有沒有辦法訪問這些約束常量,而無需將它們鏈接爲網點?我想更新這些常量,當用戶按下一個按鈕,所以在僞理想情況是:以編程方式獲取uibutton的約束條件

func buttonPressed(_ button: UIButton) { 
     button.bottomSpaceConstraint.constant += 10 
     button.horizontalAlignment.constant += 10 
} 

預先感謝您!

+0

當然,你可以訪問他們,但有很多的麻煩,圖什麼樣的約束是那些。即:'button.contraints'這是'NSLayoutConstraint'的一個數組。 – EridB

回答

3

要在Stormsyder的答案擴大,存在使用filter方法做同樣的事情,更清潔的方式。請參閱以下內容:

let bottomConstraint = button.superview!.constraints.filter({ $0.firstAttribute == .bottom && $0.firstItem == button }).first! 
let horizontalAllignmentConstraint = button.superview!.constraints.filter({ $0.firstAttribute == .centerX && $0.firstItem == button }).first! 

注意,如果不存在這些限制,以便確保他們安全或解開這將崩潰。

+0

我還沒有能夠嘗試它,因爲雖然我在IB有這些限制,他們不在button.constraints中。打印button.constraints只顯示高度和寬度的任何想法爲什麼? – iDeC

+0

啊好的,是的,因爲技術上的定位限制屬於superview。看到我更新的答案。 –

3

答案SWIFT 3:

func buttonPressed(_ button: UIButton) { 
    for constraint in button.superview!.constraints { 
     if constraint.firstAttribute == .bottom { 
      constraint.constant += 10 
     } 
    for constraint in button.constraints { 
     if constraint.firstAttribute == .centerY { 
      constraint.constant += 10 
     } 
    } 
} 
+0

@Jacob King你在回答中提出了一個錯誤,這是接近於正確的,我將更新我的回答中的更正 – Stormsyders

+0

哎呀,謝謝。我剛剛注意到我的答案中的另一個錯誤,在水平線上,最後錯過了「first!」。我會建議編輯。 –

+0

沒問題,我會從我的帖子中刪除它,因爲答案屬於你(我無法評論你的帖子,我只有24代表) – Stormsyders

0

使用這個你可以得到約束:

func buttonPressed(_ button: UIButton) { 
    let array = button?.superview?.constraints 

    for constrains in array! { 
     print(constrains.constant) 
    } 

} 
相關問題