[英]How to use SwiftUI and SceneKit together?
我在 SwiftUI 的框架內的場景中顯示了一個 SCNCylinder。 我想圍繞某個軸將它旋轉 180º。 在 SwiftUI 視圖中按下180º
(某種)按鈕后,我希望圓柱體旋轉。 目前我可以旋轉一次,但第二次按下按鈕時它不會旋轉。 我嘗試先將旋轉角度定義為 0,然后定義為 180º,但在這樣做之后,整個過程在我按下按鈕后就崩潰了。 我只是想讓氣缸在我按下按鈕后第二次旋轉。
這是我的代碼:
//SwiftUI view
struct ContentView: View {
@State var rotationAngle: Angle = .degrees(0)
var body: some View {
VStack{
Text("180º").onTapGesture {
self.rotationAngle = .zero
self.rotationAngle = .degrees(180)
}
}
SceneKitView(radius: 0.02, height: 2, angle: $rotationAngle)
.position(x: 200.0, y: 140)
.frame(width: 300, height: 300, alignment: .center)
}
}
}
//SceneKit View
struct SceneKitView: UIViewRepresentable {
@Binding var angle: Angle
let cylindernode: SCNNode
init(radius: CGFloat, height: CGFloat, angle: Binding<Angle>) {
let cylinder = SCNCylinder(radius: radius, height: height)
cylinder.firstMaterial?.diffuse.contents = UIColor.green
self.cylindernode = SCNNode(geometry: cylinder)
self.cylindernode.position = SCNVector3(0, 0, 0)
self.cylindernode.orientation = SCNVector4(0, 0, 0, 0)
cylindernode.pivot = SCNMatrix4MakeTranslation(0, -1, 0)
self._angle = angle
}
//SCNScene
func makeUIView(context: UIViewRepresentableContext<SceneKitView>) -> SCNView {
let sceneView = SCNView()
sceneView.scene = SCNScene()
sceneView.autoenablesDefaultLighting = true
sceneView.allowsCameraControl = true
sceneView.scene?.rootNode.addChildNode(cylindernode)
return sceneView
}
func updateUIView(_ sceneView: SCNView, context: UIViewRepresentableContext<SceneKitView>) {
//Rotation animation
let rotation = CABasicAnimation(keyPath: "transform.rotation")
rotation.isRemovedOnCompletion = false
rotation.duration = 5
cylindernode.addAnimation(rotation, forKey: "rotation")
cylindernode.rotation = SCNVector4(1, 0, 0, angle.radians)
}
}
}
刪除行self.rotationAngle = .zero
,代碼運行良好,但視圖未更新。 但是如果我保留這條線,那么在我按下按鈕后整個事情就會崩潰。
試試這個:但是因為你問的問題很多而且它們都很基礎,也許你應該檢查一些初學者的快速課程來學習如何設置變量......這與 Scenekit 和 SwiftUI 無關 - 它只是改變一個變量。
struct ContentView: View {
@State var rotationAngle: Angle = .degrees(0)
var body: some View {
VStack{
Text("180º").onTapGesture {
self.rotationAngle += .degrees(90)
print(self.rotationAngle)
}
SceneKitView(radius: 0.02, height: 2, angle: $rotationAngle)
.position(x: 200.0, y: 140)
.frame(width: 300, height: 300, alignment: .center)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.