代码之家  ›  专栏  ›  技术社区  ›  TheoK

在CABasicAnimation中使用#keyPath时,类型“CGPoint”没有成员“x”

  •  5
  • TheoK  · 技术社区  · 8 年前

    我正在尝试使用#keyPath语法,以获取CALayer属性,使其具有如下动画效果:

    let myAnimation = CABasicAnimation.init(keyPath: #keyPath(CALayer.position.x))
    

    我得到以下错误:

    类型“CGPoint”没有成员“x”

    我错过了什么?

    2 回复  |  直到 8 年前
        1
  •  5
  •   Martin R    8 年前

    这个 #keyPath 指令要求Objective-C属性序列为 论点 CALayer 继承自 NSObject ,但其 position 属性为 struct CGPoint ,它根本不是类,也不能 与键值编码一起使用。

    然而 CALayer公司 有一个特殊的实现 value(forKeyPath:) 它处理整个密钥路径,而不是计算第一个密钥并传递剩余的密钥路径,比较 KVC strange behavior .

    So键值编码 可以 与“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})
    

    但这并不能编译:

    print(layer.value(forKeyPath: #keyPath(CALayer.position.x)))
    // error: Type 'CGPoint' has no member 'x'
    

    这就是为什么

    let myAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.position.x))
    

    不会编译,但这会( as Reinier Melian suggested ):

    let myAnimation = CABasicAnimation(keyPath: "position.x")
    
        2
  •  1
  •   Shehata Gamal    8 年前

    position 是类型的对象中的属性 CALayer 如果要从基类访问它,则第二个关键路径将在层中获取要设置动画的属性 CALayer.position.x 不是要设置动画的CALayer对象内的属性,因此必须是 position.x 如果没有字符串“”,则无法直接编写,因为在要声明位置的类中会出现错误,因此正确的方法如下

      let myLayer = CALayer.init()
      myLayer.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
      let anim =  CABasicAnimation.init(keyPath: "position.x")
      anim.fromValue = 20
      anim.toValue = 100
      anim.duration = 1
      myLayer.add(myAnimation, forKey: "position.x")
      self.view.layer.addSublayer(myLayer)