标题是一个基本问题。试图在视图的图层上的不透明度发生更改时得到通知。
这是允许的。。。
addedView.addObserver(self, forKeyPath: #keyPath(isHidden), options: [.old, .new], context: nil)
但这并不能编译。。。
addedView.layer.addObserver(self, forKeyPath: #keyPath(opacity), options: [.old, .new], context: nil)
有什么想法吗?
来自文档:
属性名称必须是对可用属性的引用在Objective-C运行时中。[…]例如:
// ... let c = SomeClass(someProperty: 12) let keyPath = #keyPath(SomeClass.someProperty) if let value = c.value(forKey: keyPath) { print(value) }
在类中使用键路径字符串表达式时,可以通过只写属性名称来引用该类的属性,没有类名。
extension SomeClass { func getSomeKeyPath() -> String { return #keyPath(someProperty) } } print(keyPath == c.getSomeKeyPath()) // Prints "true"
所以实际上,#keyPath(...)
中的属性名称通常应该是限定的。除非属性与#keyPath
表达式在同一类中,否则应使用其封闭类名限定属性名。这是有道理的,因为编译器怎么知道你指的是哪个isHidden
属性?
#keyPath(isHidden)
恰好工作,因为您在其中写入此内容的类也碰巧具有isHidden
属性(可能是UIView
子类?(。
你应该做:
#keyPath(CALayer.opacity)
对于opacity