ios 快速的 NSLayoutConstraint

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25460382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:01:09  来源:igfitidea点击:

NSLayoutConstraint in swift

iosswiftxcode6nslayoutconstraint

提问by amau96

I am trying to convert the following code to Swift:

我正在尝试将以下代码转换为 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?

有人可以给我在 Swift 中执行此操作的新语法吗?

回答by Michael

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.

为 Swift 4 更新了代码。

回答by mt_

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)