iosswiftnslayoutconstraintnslayoutanchor

How can a `NSLayoutYAxisAnchor` be used as variable?


How can a variable of type NSLayoutYAxisAnchor be defined?

The following doesnt work, but hopefully illustrates what I mean:

let anAnchor: NSLayoutYAxisAnchor = .topAnchor

NSLayoutConstraints.activate([
   viewA.anAnchor.constraint(equalTo: viewB.anAnchor)
])

Solution

  • You can do this with the new key path feature of Swift 4:

    let anAnchor = \UIView.topAnchor
    let v1 = UIView(); let v2 = UIView() // just for testing purposes
    let constraint = v1[keyPath:anAnchor].constraint(equalTo:v2[keyPath:anAnchor])
    // now you can activate the constraint, etc.