user11243800
user11243800

Reputation:

How to add 3D shapes in Swift UI?

I want to know how to add 3D shapes (eg. Sphere) in swift UI

I have tried adding a scnscene and using that in swift UI but I get a error message

//SceneKit

class myscene: SCNScene{
 override init(){
     super.init()
 }
 required init?(coder: NSCoder) {
     fatalError("init(coder: ) has not been implemented")
 }
}

//Swift UI 

struct ContentView: View {
 var body: some View {

     let sphere = SCNSphere(radius: 2.0)
     sphere.firstMaterial?.diffuse.contents = UIColor.blue
     let spherenode = SCNNode(geometry: sphere)
     spherenode.position = SCNVector3(x: 0.0, y: 3.0, z: 0.0)
 }
}

The error message is on var body: some View { line and reads as follows :

Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

Please help me with this problem......

Upvotes: 1

Views: 2509

Answers (1)

Asperi
Asperi

Reputation: 258413

Here is simplest code to demo how to setup SceneKit scene with your sphere. Hope it helps.

import SwiftUI
import SceneKit

struct SceneKitView: UIViewRepresentable {
    func makeUIView(context: UIViewRepresentableContext<SceneKitView>) -> SCNView {
        let sceneView = SCNView()
        sceneView.scene = SCNScene()
        sceneView.allowsCameraControl = true
        sceneView.autoenablesDefaultLighting = true
        sceneView.backgroundColor = UIColor.black

        let sphere = SCNSphere(radius: 2.0)
        sphere.firstMaterial?.diffuse.contents = UIColor.blue
        let spherenode = SCNNode(geometry: sphere)
        spherenode.position = SCNVector3(x: 0.0, y: 3.0, z: 0.0)

        sceneView.scene?.rootNode.addChildNode(spherenode)
        return sceneView
    }
    
    func updateUIView(_ uiView: SCNView, context: UIViewRepresentableContext<SceneKitView>) {
        
    }
    
    typealias UIViewType = SCNView
}

struct DemoSceneKit: View {
    var body: some View {
        SceneKitView()
    }
}

struct DemoSceneKit_Previews: PreviewProvider {
    static var previews: some View {
        DemoSceneKit()
    }
}

Upvotes: 5

Related Questions