How to change bottom layout constraint in iOS, Swift

做~自己de王妃 提交于 2019-12-18 11:54:00

问题


I have scroll view as @IBOutlet

@IBOutlet weak var mainScrollView: UIScrollView!

I want to change the

"Bottom space to: Bottom Layout Guide" 

constraint programmatically.

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

How can I do this?


回答1:


Take the constraint as IBOutlet of NSLayoutConstraint.

Set the constraint outlets and change constant value by :

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



回答2:


If you are adding constraint programatically like this:

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)

Then you can update it this way:

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

And if you want that with animation you can do it this way:

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

Hope it helps.




回答3:


Create an IBOutlet for your constraint:

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

And when you need to change it call:

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

Also you can animate constraint change like that:

bottomContstraint.constant = //your value

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


来源:https://stackoverflow.com/questions/32087809/how-to-change-bottom-layout-constraint-in-ios-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!