KVO on SKView is not being called

I am trying to do KVO on an property of SKView but its not working.

I have tried it with .frame and it works like a charm, so why not also on .window ?

To clarify, I am using SpriteView in a SwiftUI app and I am trying to get the bounds of the View. What I am after is to get the following before the App starts;

print (self.convertPoint(fromView: .zero) ). When I use this in

override func didMove

I'll get Nan/NaN. However Apple Code Level Support said this about using SpriteView and getting the bounds of a view.

The reason you are receiving NaN is that you are calling these methods before the underlying SKView has been actually presented by SwiftUI, which is an event that you have no visibility into, and no way to call code when it happens.

However, when this event does occur, the SKScene’s view property will have it’s window set from nil to a UIWindow. Therefore, you could use KVO to observe when the window property is changed, and then make your calls to convertPoint once there is a non-nil window.

I have so far this:

override func didMove(to view: SKView) {
    observe.observe(object: view )
}

class Observer:SKScene {
    var kvoToken: NSKeyValueObservation?
    
    func observe(object: SKView) {
    kvoToken = object.observe(\.window , options: [ .new] ) { (object, change) in

        guard let value = change.newValue else { return }
        print("New value is: \(value)")
        print ("NEW", self.convertPoint(fromView: .zero) )
        
      }
    }
    
  deinit {
    kvoToken?.invalidate()
  }
}

I have also tried to add an observer like so :

NotificationCenter.default.addObserver(view.window, selector: #selector(test(_:)), name: NSNotification.Name(rawValue: "TestNotification"), object: nil)

The above doesn't seem to do anything. So I am kinda stuck, any help would be appreciated.



from Recent Questions - Stack Overflow https://ift.tt/3i9KPDM
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation