There is no way in SpriteKit to detect inside a custom sprite class when a node is added to the scene. This was ruled out because you have control when the sprite is added to the scene through addChild
or moveToParent
.
Spritekit MVC, UIKit. didMoveToView
, - . . presentScene
, , , . ( , , )
, , Key Value Observing (KVO) , scene
. :
override init()
{
super.init()
addObserver(self, forKeyPath: #keyPath(SKNode.scene), options: [.old, .new, .initial], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
if keyPath == #keyPath(SKNode.scene) && self.scene != nil
{
didAttachToScene()
}
}
func didAttachToScene()
{
}
deinit
{
removeObserver(self, forKeyPath: #keyPath(SKNode.scene))
}
, Windows, , , node ( KVO, , ), , , node , .
override init()
{
super.init()
addObserver(self, forKeyPath: #keyPath(SKNode.parent), options: [.old, .new, .initial], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
if keyPath == #keyPath(SKNode.parent) && self.scene != nil
{
didAttachToScene()
}
}
func didAttachToScene()
{
}
deinit
{
removeObserver(self, forKeyPath: #keyPath(self.parent))
}