如何NSLayoutYAxisAnchor
定义类型变量?
以下不起作用,但希望能说明我的意思:
let anAnchor: NSLayoutYAxisAnchor = .topAnchor
NSLayoutConstraints.activate([
viewA.anAnchor.constraint(equalTo: viewB.anAnchor)
])
如何NSLayoutYAxisAnchor
定义类型变量?
以下不起作用,但希望能说明我的意思:
let anAnchor: NSLayoutYAxisAnchor = .topAnchor
NSLayoutConstraints.activate([
viewA.anAnchor.constraint(equalTo: viewB.anAnchor)
])
您可以使用 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.
您可以像这样在Swift 4中将其用作键路径:
let anAnchor = \UIView.topAnchor
.topAnchor
不是枚举类型,它是a的属性UIView
。
因此,在 Swift 4 之前无法将其设置为变量。