Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change bottom layout constraint in iOS, Swift

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?

like image 762
Joon. P Avatar asked Aug 19 '15 06:08

Joon. P


People also ask

How do I change constraints in Xcode?

Some editing is also possible directly from the Size inspector. Clicking the Edit button in any of the constraints brings up a popover where you can change the constraint's relationship, constant, priority, or multiplier.

How do I give a constraint to button programmatically in Swift?

Add the button in the view, give it constraints and as you are using constraints, you can skip the button. frame and add widthAnchor and heightAnchor . At last activate them and keep translatesAutoresizingMaskIntoConstraints as false . Also, it will be better if you can add proper names.


2 Answers

Take the constraint as IBOutlet of NSLayoutConstraint.

enter image description here

Set the constraint outlets and change constant value by :

self.sampleConstraint.constant = 20
self.view.layoutIfNeeded()
like image 160
Ashish Kakkad Avatar answered Oct 12 '22 07:10

Ashish Kakkad


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.

like image 25
Dharmesh Kheni Avatar answered Oct 12 '22 08:10

Dharmesh Kheni