Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLayoutConstraint in swift

I am trying to convert the following code to Swift:

leftConstraint = [NSLayoutConstraint constraintWithItem:self.contentView
                                              attribute:NSLayoutAttributeLeft
                                              relatedBy:0
                                                 toItem:self.view
                                              attribute:NSLayoutAttributeLeft
                                             multiplier:1.0
                                               constant:0];
[self.view addConstraint:leftConstraint];

Can someone give me the new syntax to do it in Swift?

like image 878
amau96 Avatar asked Aug 23 '14 09:08

amau96


People also ask

What is NSLayoutConstraint Swift?

The relationship between two user interface objects that must be satisfied by the constraint-based layout system.


1 Answers

Copy & paste from the documentation:

convenience init(item view1: AnyObject!,
            attribute attr1: NSLayoutAttribute,
         relatedBy relation: NSLayoutRelation,
               toItem view2: AnyObject!,
            attribute attr2: NSLayoutAttribute,
      multiplier multiplier: CGFloat,
                 constant c: CGFloat)

So your code translates to

let leftConstraint = NSLayoutConstraint(item: self.contentView, 
                                   attribute: .left, 
                                   relatedBy: .equal,
                                      toItem: self.view,
                                   attribute: .left, 
                                  multiplier: 1.0, 
                                    constant: 0.0);
self.view.addConstraint(leftConstraint);

Code updated for Swift 4.

like image 181
Michael Avatar answered Sep 29 '22 09:09

Michael