NSLayoutConstraint 并分配一个 int 变量

NSLayoutConstraint and assigning a variable that is an int

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

我有一个如下所示的 NSLayoutConstraint:

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

并且工作正常。当我将其更改为

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)

它给我一个错误说明:

/Users/jt/tmp-ios/autolayout-test/autolayout-test/ViewController.swift:31:30: Cannot find an initializer for type 'NSLayoutConstraint' that accepts an argument list of type '(item: UIView, attribute: NSLayoutAttribute, relatedBy: NSLayoutRelation, toItem: UIView!, attribute: NSLayoutAttribute, multiplier: Int, constant: Int)'

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

Swift 不会自动将类型 Int 的变量转换为类型 CGFloat 的变量。您必须明确转换:

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

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

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

var verticalStartingPoint: CGFloat = 0