SWIFTUI和核心运动

问题描述 投票:1回答:1

我正在尝试在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()
    }
}
swiftui core-motion
1个回答
0
投票

这里是可能的解决方法

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
© www.soinside.com 2019 - 2024. All rights reserved.