【发布时间】:2021-09-06 05:28:12
【问题描述】:
我正在尝试为 NSImageView 中的图像更改设置动画。这是一个纯粹的学术问题,我处于 macOS 绑定框架的限制范围内。
请考虑型号:
class Model: NSObject {
/// Image object for the NSImageView
@objc dynamic var image: NSImage?
/// The target action for button `A`.
/// Changes the image inside model.
/// The change is not a KVO compliment because such a change is 'inside' the model.
@objc func a() {
self.image = NSImage(named: "a")
}
/// The target action for the button B
/// In the window UI
@objc func b() {
self.image = NSImage(named: "b")
}
}
这是圣经中最简单和严格的绑定示例 (What Are Cocoa Bindings?)。我想要实现的区别是让用户可以看到图像更改过程。
我会截取从 NSObjectController 移动到 NSImageView 的每一个新图像,并与旧图像一起传输。
class AnimatedImageView: NSImageView {
override func setValue(_ value: Any?, forKey key: String) {
// The code execution is never through this point.
if key == "image" {
self.transition(value as! NSImage?)
} else {
super.setValue(value, forKey: key)
}
}
private func transition(_ newImage:NSImage?) {
let transition = CATransition()
transition.duration = 1
transition.type = .fade
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
self.layer?.add(transition, forKey: nil)
self.image = newImage
}
}
尝试覆盖方法setValue(_:forKey:) 不成功。
尽管如此,我知道bind(...) 方法运行良好,应用程序本身运行良好,动画除外。
我错过了什么?
请在附件中找到项目源是there。
【问题讨论】:
-
是什么让您期望
setValue被调用?或者换一种说法:你认为应该给setValue打电话? -
最终目标是什么?你想达到什么目标?
-
@Sajjon 我在
ImageView.中实现淡入/淡出NSImage更改 -
@Sweeper 我希望
setValue将NSValue? as Any?从模型传递到KVO 的MyImageView.image。我之前用NSTableColumn子类做了这样的把戏,一切都很好,但这次我坚持了这个问题,MyImageView不要调用覆盖setValue. -
如果你使用值绑定然后覆盖
objectValue属性。
标签: swift appkit key-value-observing cocoa-bindings nsimageview