如何使用SwiftUI更新不同的视图?

时间:2019-12-12 14:57:17

标签: rotation swiftui scenekit swift5

我的目标是制作一个程序,其中使用SwiftUI按钮通过SceneKit中的SCNView更新。我在SCNCylinder中的SCNView中有一个圆柱体,位于SwiftUI的框架中。我希望我的气缸在按下按钮后旋转大约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

}

按下按钮后,我希望圆柱体旋转。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

只需将startingAngle设置为0

@State var rotationAngle: Float = 0