[英]How can I pass Binding<CMMotionManager> in SwiftUI preview?
我將我的應用程序的 motionManager 從 ContentView 傳遞到 SecondView,它工作正常,但我不知道如何在我的 SecondView 的預覽中傳遞它,它需要參數類型Binding<CMMotionManager>
import SwiftUI
import CoreMotion
struct ContentView: View {
@State private var motionManager = CMMotionManager()
let queue = OperationQueue()
@State private var roll = Double.zero
var body: some View {
NavigationView {
VStack {
Text("Roll is: \(roll)")
.font(.largeTitle)
NavigationLink {
SecondView(motionManager: $motionManager)
} label: {
Text("Change View")
}
}
.onAppear {
//Detect device motion
self.motionManager.startDeviceMotionUpdates(to: self.queue) { (data: CMDeviceMotion?, error: Error?) in
guard let data = data else {
print("Error: \(error!)")
return
}
let attitude: CMAttitude = data.attitude
DispatchQueue.main.async {
self.roll = attitude.roll
}
}
}
}
}
}
import SwiftUI
import CoreMotion
struct SecondView: View {
@Binding var motionManager: CMMotionManager
var body: some View {
Text("Hello, World!")
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView(motionManager: Binding<CMMotionManager>) <-- //What should i pass here??
}
}
您不需要CMMotionManager
的狀態/綁定,因為它是引用類型的,並且正如您自己提到的,將是單個 object。
所以只需在常規屬性中按引用使用它
struct ContentView: View {
private var motionManager = CMMotionManager() // << here !!
//...
}
struct SecondView: View {
let motionManager: CMMotionManager // << here !!
var body: some View {
Text("Hello, World!")
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView(motionManager: CMMotionManager()) // << here !!
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.