oneshot
oneshot

Reputation: 663

Could not cast value of type 'UIView' to 'SKView' (removed Storyboard)

I'm working for the first time with SpriteKit and I have an issue at app launch:

Could not cast value of type 'UIView' (0x2038a8848) to 'SKView' (0x2039f2658).

This question makes clear that you have to set the GameViewController's view custom class to SKView and explain how to do it using Storyboard. The problem is that I'm trying to do it programmatically, as i removed the Storyboard, and I have no idea how to do it. As I'm used to UIKit, this has never gave me issues of any kind.

So, in AppDelegate i say:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    let window = UIWindow(frame: UIScreen.main.bounds)
    window.rootViewController = GameViewController()
    window.makeKeyAndVisible()
    self.window = window
    return true
}

In GameViewController:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let skView = view as! SKView
    skView.ignoresSiblingOrder = true

    gameScene = GameScene(size: view.frame.size)
    gameScene!.scaleMode = .aspectFill
    gameScene!.gameSceneDelegate = self
    
    show(gameScene!, animated: true)
    
}

All I get is the up above error when i try do downcast the VC view as a SKView. Can anybody shine a light on how to launch the app programmatically under these conditions please?

Upvotes: 1

Views: 595

Answers (2)

Sweeper
Sweeper

Reputation: 274500

This is where your mistake is:

let skView = view as! SKView

You are assuming that self.view is an instance of SKView, but it isn't. It's a UIView, just like how in the storyboard, the root view by default has the class UIView.

You should instead do:

let skView = SKView()
view = skView

To set the root view to an instance of SKView.

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100541

The view controllers's view in storyboard has a SKView class name being set there , when you delete it you roll to usual vc's view so add this to your GameViewController

override func loadView() {
    self.view = SKView() 
}

Tip : loadView is where you should init the view controller's view when there is no associated storyboard/xib

Upvotes: 1

Related Questions