如何在iOS,Swift中更改底部布局约束

时间:2015-08-19 06:17:08

标签: ios xcode swift storyboard nslayoutconstraint

我的滚动视图为@IBOutlet

@IBOutlet weak var mainScrollView: UIScrollView!

我想改变

"Bottom space to: Bottom Layout Guide" 

以编程方式约束。

First Item : Bottom Layout Guide.Top
Relation : Equal
Second Item: Scroll View.Bottom
Constant: 0 -> 50 // (I want to change this programmatically)
Priority: 1000
Multiplier: 1

我该怎么做?

3 个答案:

答案 0 :(得分:29)

将约束作为IBOutlet的{​​{1}}。

enter image description here

设置约束出口并通过以下方式更改NSLayoutConstraint值:

constant

答案 1 :(得分:19)

如果您以编程方式添加约束:

var constraintButton = NSLayoutConstraint (item: buttonPlay, 
                                           attribute: NSLayoutAttribute.Bottom, 
                                           relatedBy: NSLayoutRelation.Equal, 
                                           toItem: self.view, 
                                           attribute: NSLayoutAttribute.Bottom, 
                                           multiplier: 1,
                                           constant: 0)
// Add the constraint to the view
self.view.addConstraint(constraintButton)

然后你可以这样更新:

self.constraintButton.constant = 50
self.view.layoutIfNeeded()

如果您想要动画,可以这样做:

self.view.layoutIfNeeded()
UIView.animateWithDuration(1, animations: {
    self.constraintButton.constant = 50
    self.view.layoutIfNeeded()
})

希望它有所帮助。

答案 2 :(得分:7)

为您的约束创建IBOutlet

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

当你需要改变时,请致电:

bottomContstraint.constant = //your value
view.layoutIfNeeded()

您也可以像下那样为约束更改设置动画:

bottomContstraint.constant = //your value

UIView.animateWithDuration(0.5, animations: {
  self.view.layoutIfNeeded()
})