简体   繁体   中英

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

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.

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.

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