How can a `NSLayoutYAxisAnchor` be used as variable?

3.6k Views Asked by At

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)
])
2

There are 2 best solutions below

0
On BEST ANSWER

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.
1
On

You can use it as a keypath in Swift 4 like this:

let anAnchor = \UIView.topAnchor

.topAnchor is not an enumeration type, it's a property for a UIView.
Therefore, it is not possible before Swift 4 to set it as a variable.