如何在SwiftUI中使用onReceive从ObservedObject获取数据?

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

在我的SwiftUI应用中,每次值更改时,我都需要从ObservedObject获取数据。我知道我们可以使用.onReceive来做到这一点?我不太了解Apple的文档。我不知道该怎么办。

我的代码:

import SwiftUI
import CoreLocation

struct Compass: View {

  var locationManager = CLLocationManager()
  @ObservedObject var location: LocationManager = LocationManager()
  @State private var angle: CGFloat = 0

  var body: some View {
    VStack {
      Image("arrow")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: 300, height: 300)
        .modifier(RotationEffect(angle: -CGFloat(self.angle.degreesToRadians)))
        .onReceive(location, perform: {
          withAnimation(.easeInOut(duration: 1.0)) {
            self.angle = self.location.heading
          }
        })

      Text(String(self.location.heading.degreesToRadians))
        .font(.system(size: 20))
        .fontWeight(.light)
        .padding(.top, 15)
    }
  }
}

struct RotationEffect: GeometryEffect {
  var angle: CGFloat

  var animatableData: CGFloat {
    get { angle }
    set { angle = newValue }
  }

  func effectValue(size: CGSize) -> ProjectionTransform {
    return ProjectionTransform(
      CGAffineTransform(translationX: -150, y: -150)
        .concatenating(CGAffineTransform(rotationAngle: angle))
        .concatenating(CGAffineTransform(translationX: 150, y: 150))
    )
  }
}

在我的LocationManager类中,有一个标题为Published的变量,这是我要检查的变量。]​​>

每次箭头移动时,标题值更改时就需要获取数据以创建动画。对于某些原因,我需要使用CGAffineTransform。

在我的SwiftUI应用中,每次值更改时,我都需要从ObservedObject获取数据。我知道我们可以使用.onReceive来做到这一点?我不太了解Apple的文档。我...

swift swiftui
1个回答
0
投票

您需要听objectWillChange通知,闭包有一个参数,它是ObservableObject上设置的新值(我假设它是标题,如果我输入错了,请更正)]

© www.soinside.com 2019 - 2024. All rights reserved.