Search code examples
swiftxcodeswiftuiscenekit

How to change the background color of a SceneView 3D Object in SwiftUI


Does anybody knows how to change the color of the background of a SceneView object? I'm trying by just placing the background attribute to the SceneView, but it doesn't change it, still with a default background.In this case I wanted to the background be green, but it's keeps gray/white

import SwiftUI
import SceneKit

struct ContentView: View {
    var body: some View {
    
        ZStack{
            Color.red
            SceneView(
                scene: SCNScene(named: "Earth.scn"),
                options: [.autoenablesDefaultLighting,.allowsCameraControl]
            )
            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/2, alignment: .center)
            .background(Color.green)
            .border(Color.blue, width: 3)
        
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Solution

  • The gray that you are seeing is from SCNScene's background property. You need to set this to UIColor.green.

    struct ContentView: View {
        var body: some View {
            
            ZStack{
                Color.red
                SceneView(
                    scene: {
                        let scene = SCNScene(named: "Earth.scn")!
                        scene.background.contents = UIColor.green /// here!
                        return scene
                    }(),
                    options: [.autoenablesDefaultLighting, .allowsCameraControl]
                )
                .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/2, alignment: .center)
                .border(Color.blue, width: 3)
                
            }
        }
    }
    

    Result:

    green background in SceneView