The*_*eoK 5 calayer cabasicanimation ios swift
我正在尝试使用 #keyPath 语法来获取 CALayer 属性来为它设置动画:
let myAnimation = CABasicAnimation.init(keyPath: #keyPath(CALayer.position.x))
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
类型 'CGPoint' 没有成员 'x'
我错过了什么?
该#keyPath指令需要一个 Objective-C 属性序列作为参数。CALayer继承自NSObject,但它的position
属性是struct CGPoint,它根本不是一个类,不能与 Key-Value 编码一起使用。
但是, CALayer有一个特殊的实现,value(forKeyPath:)
它处理整个密钥路径,而不是评估第一个密钥并传递剩余的密钥路径,比较 KVC 奇怪的行为。
所以键值编码可以与“position.x”一起使用,但编译器不知道这种特殊处理。例如,这一切都编译并运行:
let layer = CALayer()
layer.position = CGPoint(x: 4, y: 5)
print(layer.value(forKeyPath: "position")) // Optional(NSPoint: {4, 5}
print(layer.value(forKeyPath: "position.x")) // Optional(4)
print(layer.value(forKeyPath: #keyPath(CALayer.position))) // Optional(NSPoint: {4, 5})
Run Code Online (Sandbox Code Playgroud)
但这不能编译:
print(layer.value(forKeyPath: #keyPath(CALayer.position.x)))
// error: Type 'CGPoint' has no member 'x'
Run Code Online (Sandbox Code Playgroud)
这就是为什么
let myAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.position.x))
Run Code Online (Sandbox Code Playgroud)
不编译,但这样做(如 Reinier Melian 建议的那样):
let myAnimation = CABasicAnimation(keyPath: "position.x")
Run Code Online (Sandbox Code Playgroud)