【问题标题】:How to update different views using SwiftUI?如何使用 SwiftUI 更新不同的视图?
【发布时间】:2023-03-22 03:34:02
【问题描述】:

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

}

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

【问题讨论】:

    标签: rotation swiftui scenekit swift5


    【解决方案1】:

    只需将startingAngle设置为0

    @State var rotationAngle: Float = 0
    

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 2021-01-03
      • 2022-10-21
      相关资源
      最近更新 更多