简体   繁体   中英

NSLayoutConstraint and assigning a variable that is an int

I feel this might be a very simple question as I'm just getting started with Swift but am a bit confused about this behavior.

I have an NSLayoutConstraint that looks like this:

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

and works fine. When I change it to

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)

It gives me an error stating:

/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)'

But I'm not sure why? It seems like I'm just assinging a variable in this case.

Swift won't automatically convert a variable of type Int to a variable of type CGFloat . You have to convert explicitly:

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

Swift will automatically convert a numeric integer literal (like “ 0 ”) to any numeric type. That's why your first try worked.

Instead of converting in the call to NSLayoutConstraint , you could change the variable's type instead:

var verticalStartingPoint: CGFloat = 0

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM