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?
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.