Search code examples
iosswiftsprite-kitbackground-color

The background color operators are not working in swift


I am trying to make a button in Swift and I want to set the background color to white but it stays system grey no matter what.

I tried setting the bg color under super.viewDidLoad() like this:

//
//  GameViewController.swift
//  Button
//
//  Created by Damien Desaulniers on 2023-07-08.
//

import UIKit
import SpriteKit
import GameplayKit

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        // Load 'GameScene.sks' as a GKScene. This provides gameplay related content
        // including entities and graphs.
        if let scene = GKScene(fileNamed: "GameScene") {
            
            // Get the SKScene from the loaded GKScene
            if let sceneNode = scene.rootNode as! GameScene? {
                
                // Copy gameplay related content over to the scene
                sceneNode.entities = scene.entities
                sceneNode.graphs = scene.graphs
                
                // Set the scale mode to scale to fit the window
                sceneNode.scaleMode = .aspectFill
                
                // Present the scene
                if let view = self.view as! SKView? {
                    view.presentScene(sceneNode)
                    
                    view.ignoresSiblingOrder = true
                    
                    view.showsFPS = true
                    view.showsNodeCount = true
                }
            }
        }
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if UIDevice.current.userInterfaceIdiom == .phone {
            return .allButUpsideDown
        } else {
            return .all
        }
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }
}

Here is the game scene as well:

import SpriteKit
import GameplayKit

class GameScene: SKScene {

var entities = [GKEntity]()
var graphs = [String : GKGraph]()

private var lastUpdateTime : TimeInterval = 0
private var label : SKLabelNode?
private var spinnyNode : SKShapeNode?

override func sceneDidLoad() {

    self.lastUpdateTime = 0
    
    // Get label node from scene and store it for use later
    self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
    if let label = self.label {
        label.alpha = 0.0
        label.run(SKAction.fadeIn(withDuration: 2.0))
    }
    
    // Create shape node to use during mouse interaction
    let w = (self.size.width + self.size.height) * 0.05
    self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.3)
    
    if let spinnyNode = self.spinnyNode {
        spinnyNode.lineWidth = 2.5
        
        spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
        spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
                                          SKAction.fadeOut(withDuration: 0.5),
                                          SKAction.removeFromParent()]))
    }
}


func touchDown(atPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.green
        self.addChild(n)
    }
}

func touchMoved(toPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.blue
        self.addChild(n)
    }
}

func touchUp(atPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.red
        self.addChild(n)
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let label = self.label {
        label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut")
    }
    
    for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}

override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}


override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
    
    // Initialize _lastUpdateTime if it has not already been
    if (self.lastUpdateTime == 0) {
        self.lastUpdateTime = currentTime
    }
    
    // Calculate time since last update
    let dt = currentTime - self.lastUpdateTime
    
    // Update entities
    for entity in self.entities {
        entity.update(deltaTime: dt)
    }
    
    self.lastUpdateTime = currentTime
}
}

As well as setting the bg color to white in the main view, my other attempt: enter image description here

But nothing works. :(


Solution

  • I feel like your problem is that you're trying to instatiate an object out of a file that does not exist in your project.

    if let scene = GKScene(fileNamed: "GameScene") {
        // the compiler will never enter this block
    }
    

    Here you're looking for a GameScene.sks file, but as far as I can see from your screenshot you deleted it, and the whole if block is never executed.

    Fastest way to fix it, since you've basically added zero code to your project yet, is to create a new Game project from XCode, which comes with a built-in GameScene.sks file that you're missing.

    Once you've fixed the issue above, changing the background color is trivial. Just add these lines in sceneDidLoad() of GameScene:

    self.backgroundColor = SKColor.white
    

    Or, inGameViewController, in viewDidLoad()

    self.view.backgroundColor = .white
    

    depending on what you want to achieve.