18

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?

0

2 Answers 2

31

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.

1
  • 6
    Not relatedBy:0, is now relatedBy:.Equal, Sep 19, 2014 at 17:25
-2

Try this:

var leftConstrains:NSLayoutConstraint = NSLayoutConstraint(item: self.contentView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)

self.contentView.addConstraint(leftConstrains)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.