You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中视图背景颜色设置无效问题求助

Swift中设置视图背景为白色无效的解决办法

我在Swift项目中制作按钮,想要将视图背景色设置为白色,但无论怎么操作它都保持系统灰色。我尝试在super.viewDidLoad()之后设置背景色,代码如下:

GameViewController.swift 代码

//
//  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
    }
}

GameScene.swift 代码

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
}
}

除了在代码中设置主视图背景色,我还尝试过在界面编辑器中直接设置视图背景色,但所有方法都不起作用。


解决办法

问题的核心是你使用了SpriteKit的SKScene,它会直接覆盖在SKView之上,所以你设置UIViewController的view背景色会被SKScene遮挡。需要同时设置SKScene和SKView的背景色:

  1. 设置SKScene的背景色
    在GameScene的sceneDidLoad方法中添加一行代码:
override func sceneDidLoad() {
    self.lastUpdateTime = 0
    self.backgroundColor = .white // 添加这行设置场景背景为白色
    
    // 其他原有代码...
}
  1. 设置SKView的背景色(可选但更保险)
    在GameViewController的viewDidLoad中,获取到SKView后补充设置背景色:
if let view = self.view as! SKView? {
    view.backgroundColor = .white // 添加这行
    view.presentScene(sceneNode)
    
    // 其他原有代码...
}

因为你的SKScene使用了.aspectFill的缩放模式,当场景尺寸与视图不匹配时,边缘会露出SKView的背景,所以同时设置两者的背景色才能确保整个界面都是白色。

内容的提问来源于stack exchange,提问作者MecMcCallister

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:10:03