SWIFTUI 和 Core Motion

SWIFTUI and Core Motion

我正在尝试在 SWIFTUI 视图中显示加速度计数据。这段代码可以打印到控制台,但我不明白如何将它放入视图中,以便我可以在 SWIFTUI 中使用它。

import SwiftUI
import CoreMotion


struct AccelerometerView: View {

    let motionManager = CMMotionManager()
    let queue = OperationQueue()


    var body: some View {

        VStack{
            Text("accelerate:").onAppear {
                print("ON APPEAR")
                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

                    print("pitch: \(attitude.pitch)")
                    print("yaw: \(attitude.yaw)")
                    print("roll: \(attitude.roll)")
                }
            }//.onappear

            //Text("Pitch:\(attitude.pitch)")

        }//Vstack

    }//view
}//struct

struct AccelerometerView_Previews: PreviewProvider {
    static var previews: some View {
        AccelerometerView()
    }
}

这是可能的解决方案

struct AccelerometerView: View {

    let motionManager = CMMotionManager()
    let queue = OperationQueue()

    @State private var pitch = Double.zero
    @State private var yaw = Double.zero
    @State private var roll = Double.zero

    var body: some View {

        VStack{
            Text("Pitch: \(pitch)")
            Text("Yaw: \(yaw)")
            Text("Roll: \(roll)")
        }//Vstack
        .onAppear {
                print("ON APPEAR")
                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

                    print("pitch: \(attitude.pitch)")
                    print("yaw: \(attitude.yaw)")
                    print("roll: \(attitude.roll)")

                    DispatchQueue.main.async {
                        self.pitch = attitude.pitch
                        self.yaw = attitude.yaw
                        self.roll = attitude.roll
                    }
                }
            }//.onappear
    }//view
}//struct