NSLayoutConstraint 并分配一个 int 变量

tim*_*one 4 ios nslayoutconstraint swift

我觉得这可能是一个非常简单的问题,因为我刚刚开始使用 Swift,但对这种行为有点困惑。

我有一个如下所示的 NSLayoutConstraint:

let verticalConstraint = NSLayoutConstraint(item: newView, 
         attribute: NSLayoutAttribute.CenterY, 
        relatedBy: NSLayoutRelation.Equal, 
        toItem: view, 
        attribute: NSLayoutAttribute.CenterY, 
        multiplier: 1, 
        constant: 0)
Run Code Online (Sandbox Code Playgroud)

并且工作正常。当我把它改成

class ViewController: UIViewController {

  let newView = UIView()
  var verticalStartingPoint = 0

  override func viewDidLoad() {
    super.viewDidLoad()
    newView.backgroundColor = UIColor.blueColor()
    newView.setTranslatesAutoresizingMaskIntoConstraints(false)
    view.addSubview(newView)

    // not the part that is problem
    let horizontalConstraint = NSLayoutConstraint(item: newView, 
         attribute: NSLayoutAttribute.CenterX, 
         relatedBy: NSLayoutRelation.Equal, 
         toItem: view, 
         attribute: NSLayoutAttribute.CenterX, 
         multiplier: 1, 
         constant: 0)
    view.addConstraint(horizontalConstraint)


    var verticalConstraint = NSLayoutConstraint(item: newView, 
        attribute: NSLayoutAttribute.CenterY, 
       relatedBy: NSLayoutRelation.Equal, 
      toItem: view, attribute: NSLayoutAttribute.CenterY, 
      multiplier: 1, 
      constant: self.verticalStartingPoint  // <- seems to be error
)
view.addConstraint(verticalConstraint)
Run Code Online (Sandbox Code Playgroud)

它给了我一个错误说明:

/Users/jt/tmp-ios/autolayout-test/autolayout-test/ViewController.swift:31:30: 找不到类型“NSLayoutConstraint”的初始值设定项,它接受类型为“(项目:UIView,属性:NSLayoutAttribute)的参数列表, relatedBy: NSLayoutRelation, toItem: UIView!, 属性: NSLayoutAttribute, multiplier: Int, constant: Int)'

但我不确定为什么?在这种情况下,我似乎只是在分配一个变量。

rob*_*off 5

Swift 不会自动将 type 变量转换为 typeInt变量CGFloat。您必须显式转换:

var verticalConstraint = NSLayoutConstraint(item: newView,
    attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal,
    toItem: view, attribute: NSLayoutAttribute.CenterY,
    multiplier: 1, constant: CGFloat(self.verticalStartingPoint))
Run Code Online (Sandbox Code Playgroud)

Swift 会自动将数字整数文字(如“ 0”)转换为任何数字类型。这就是您的第一次尝试成功的原因。

NSLayoutConstraint您可以改为更改变量的类型,而不是在对 的调用中进行转换:

var verticalStartingPoint: CGFloat = 0
Run Code Online (Sandbox Code Playgroud)