user1763430 user1763430 - 1 year ago 380
iOS Question

Swift - Adding background image behind a Sprite Kit Scene in View Controller

I am trying to add a background image in my view controller so my sprite kit game scenes can be in the foreground. It's important for me for my background image to stay on screen while the game scenes transition to each other. The problem I am having is how to place the subview I created for my background to be behind my skscene, at the moment my background image is in front of my game scene and all you can see is the image

doesn't seem to work. The following is my viewDidLoad Thanks

import UIKit
import SpriteKit

class GameViewController: UIViewController {

override func viewDidLoad() {

let scene = MainMenuScene(size: CGSize(width: 1536, height: 2048))
let skView = self.view as! SKView

scene.scaleMode = .AspectFill

let backgroundImageView = UIImageView(image: UIImage(named: "bg.jpg"))
backgroundImageView.frame = view.frame
backgroundImageView.contentMode = .ScaleAspectFill


Answer Source

What you're describing can't be done with UIKit because your view can't be visible behind the SKView which renders your scene.

In iOS 8+ you can use the SKView's allowsTransparency property. Documentation states:

This property tells the drawing system as to how it should treat the view. If set to NO, the drawing system treats the view as fully opaque, which allows the drawing system to optimize some drawing operations and improve performance. If set to YES, the drawing system composites the view normally with other content. The default value of this property is NO.

But in my opinion this is not the best solution. The best solution is to use Sprite Kit, but the problem is you can't preserve nodes across scenes. You must add the node again during each scene transition. This is why I do not use Apple's scene transitions the way the documentation describes. Instead I use my own custom SKNodes and make my own custom transitions using those nodes, which I highly recommend you do. I gave a detailed answer about this here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download