首页 > 解决方案 > 如何使用 SwiftUI 更新不同的视图?

问题描述

我的目标是制作一个程序,在该程序中,我使用 SwiftUI 按钮通过 SceneKit 中的 SCNView 进行更新。我在 SwiftUI 的框架内有一个SCNCylinder圆柱体SCNView。我希望我的气缸在按下按钮后旋转大约 180°。在我当前的代码中,我使用@State@Binding更新了视图。但是不知何故,一旦我运行代码,圆柱体就会旋转,而不是等待我触摸按钮。不知道为什么会这样

这是我的代码:

struct ContentView: View {
    @State var rotationAngle: Float = 180
      var body: some View {
       VStack{ 
          Button(action: {
            // What to perform
            self.rotationAngle = 180
        }) {
            // How the button looks like
            Text("180°")
                .frame(width: 100, height: 100)
                .position(x: 225, y: 500)
        }


        SceneKitView(angle: self.$rotationAngle)
            .frame(width: 300, height: 300)
            .position(x: 225, y: 0)


    }
  } 
}

struct SceneKitView: UIViewRepresentable {
    @Binding var angle: Float

func degreesToRadians(_ degrees: Float) -> CGFloat {
    return CGFloat(degrees * .pi / 180)
}

func makeUIView(context: UIViewRepresentableContext<SceneKitView>) -> SCNView {

    let sceneView = SCNView()
    sceneView.scene = SCNScene()
    sceneView.allowsCameraControl = true
    sceneView.autoenablesDefaultLighting = true
    sceneView.backgroundColor = UIColor.white
    sceneView.frame = CGRect(x: 0, y: 10, width: 0, height: 1)
    return sceneView
}

func updateUIView(_ sceneView: SCNView, context: UIViewRepresentableContext<SceneKitView>) {


    let cylinder = SCNCylinder(radius: 0.02, height: 2.0)
    let cylindernode = SCNNode(geometry: cylinder)
    cylindernode.position = SCNVector3(x: 0, y: 0, z: 0)
    cylinder.firstMaterial?.diffuse.contents = UIColor.green  

    cylindernode.pivot = SCNMatrix4MakeTranslation(0, -1, 0)

    let rotation = SCNAction.rotate(by: self.degreesToRadians(self.angle), around: SCNVector3(1, 0, 0), duration: 5)

    sceneView.scene?.rootNode.addChildNode(cylindernode)


    cylindernode.runAction(rotation)


}
typealias UIViewType = SCNView

}

我希望气缸在按下按钮后旋转。请帮我解决这个问题。

标签: rotationswiftuiscenekitswift5

解决方案


只需将startingAngle设置为0

@State var rotationAngle: Float = 0

推荐阅读