问题
In my SpriteKit game, I want to add a property observer on the fieldBitMask
property for the SKPhysicsBody
of my sprites. I want to be informed when the fieldBitMask
property changes so that I can take some action.
I overrode SKPhysicsBody
but when I tried assigning the overridden class to a sprite node like a normal SKPhysicsBody
object I got a bunch of errors. I also thought about making an extension for SKPhysicsBody, but Apple documentation says, “Extensions can add new functionality to a type, but they cannot override existing functionality.” So it would seem that I can't override the fieldBitMask
property this way to make it a property observer.
I know how to create a property observer in a new custom class which I create. But what is the best way to add a property observer to an existing property in a class that is part of the Apple library?
回答1:
I think you can use the Key Value Observing. You can add observer to a property changing.
You should implement observeValue(forKeyPath:of:change:context:)
method in your observer class.
Here you can find Swift example ("Key-Value Observing" part).
回答2:
You can subclass SKPhysicsBody
like that:
class Subclass: SKPhysicsBody {
override var fieldBitMask: UInt32 {
didSet {
print(fieldBitMask)
}
}
}
来源:https://stackoverflow.com/questions/46484188/add-a-property-observer-on-an-existing-property-in-an-ios-library-class