rotation - 如何使用 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
}
我希望气缸在按下按钮后旋转。请帮我解决这个问题。
解决方案
只需将startingAngle设置为0
@State var rotationAngle: Float = 0
推荐阅读
- vue.js - 如何在 nuxt axios instanse 中添加令牌
- python - 如何使用日期作为过滤器将列添加到数据框中
- docker - 如何通过“docker logs”获取嵌入在 docker 容器中的 VM 的控制台日志
- scala - 如何解决编译时的类型错误:Any to T?
- mysql - MySQL 根据存储过程中传递的 id 添加新的 LIST 分区?
- c++ - 我的应用程序名称在运行后更改,但它没有文件扩展名,我希望它在 .exe 中
- c++ - 数独求解器生成值为 50+ 的单元格
- c# - 我是否正确理解如何通过 RSA + AES 加密 TCP 流量?
- javascript - 使用过滤器获取对象的数据
- asp.net-core-mvc - ASP.NET Core MVC 中的类别/子类别(/subsubcategory*)路由