2016-11-04 77 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) 
    } 

}