如何更改 iOS、Swift 中的底部布局约束

How to change bottom layout constraint in iOS, Swift

我的滚动视图是@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

我该怎么做?

取约束为IBOutlet of NSLayoutConstraint.

设置约束出口并将constant值更改为:

self.sampleConstraint.constant = 20
self.view.layoutIfNeeded()

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

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()
})

希望对您有所帮助。

为您的约束创建一个 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()
})