NSLayoutConstraint in swift

2019-04-18 09:34发布

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?

2条回答
地球回转人心会变
2楼-- · 2019-04-18 10:17

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)
查看更多
smile是对你的礼貌
3楼-- · 2019-04-18 10:19

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.

查看更多
登录 后发表回答