2

First, I've reviewed the related questions:

None of those provided a clear answer for me, I'm unable to present a controller that has an SKView in it from my main ViewController, example:

import UIKit
import SceneKit
import SpriteKit

class ViewController: UIViewController {
  var sceneView: SCNView!
  var gameScene = GameScene()
  var spriteScene: OverlayScene!

  override func viewDidLoad() {
    super.viewDidLoad()

    sceneView = SCNView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
    sceneView.scene = gameScene
  }

  func showModal() {
    let popupViewController = PopupViewController()
    popupViewController.modalPresentationStyle = .popover
    present(popupViewController, animated: true, completion: nil)
  }  
}

But the issue seems to be when the PopupViewController is called:

import UIKit
import SpriteKit

class PopupViewController:UIViewController {
  var sceneView:SKView!
  var spriteScene:PopupScene!

  override func viewDidLoad() {
    view.backgroundColor = UIColor.green
    view.scene = spriteScene

    super.viewDidLoad()
  }
}

The error is raised:

Could not cast value of type 'UIView' (0x1b48c69c8) to 'SKView' (0x1b3b254b0).
rmaddy
  • 314,917
  • 42
  • 532
  • 579
JP Silvashy
  • 46,977
  • 48
  • 149
  • 227
  • 1
    I am just quickly glancing at this, but the PopupViewController is a UIViewController. I don't work with scenes too much- but it looks like instead of setting the scene of the 'sceneView' on 'PopupViewController', you are setting the scene on the view(which is a UIView by default). So you may need to set up that 'sceneView' and then set the scene on that? – Kayla Galway Jan 19 '18 at 19:24
  • 1
    Yeah, `view` in a `UIViewController` is a `UIView`. Looks like you need to set `view = sceneView` in `loadView` or `viewDidLoad`. – Nathan Hitchings Jan 19 '18 at 19:28
  • Thinking a little more, it probably needs to happen in `loadView`. Not 100% sure though. – Nathan Hitchings Jan 19 '18 at 19:35

1 Answers1

2

Looking at your answer, you appear to be using the main view of your PopupViewController to add the scene to, rather than the new sceneView that you declared. The first way to fix this is, as said by Nathan Hitchings in the comments, to override loadView and set self.view = sceneView. The other option is to open your storyboard or .xib and set the class type of the main view to be SKView and then you can delete the sceneView variable entirely and work with self.view. Both essentially do the same thing, but in two different ways. Ensure that you give sceneView a value before using it too, as currently it appears to stay uninitialised. Let me know if you need me to clarify anything.

The first option would look something like this:

override func loadView() {
    sceneView = SKView()
    sceneView.backgroundColor = .white

    self.view = sceneView
}
Jack Chorley
  • 2,309
  • 26
  • 28