0

我正在构建一个 SwiftUI 应用程序,它根据用户纬度/经度显示数据。我的代码基于框架开发人员提供的这个示例。

使用 SwiftUI,我的LocationManager设置为:

class LocationViewModel: NSObject, ObservableObject, CLLocationManagerDelegate{
  
    @Published var userLatitude: Double = 0.0
    @Published var userLongitude: Double = 0.0
  
  private let locationManager = CLLocationManager()
  
  override init() {
    super.init()
    self.locationManager.delegate = self
    self.locationManager.distanceFilter = 100.0
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
  }

  
  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.last else { return }
    userLatitude = location.coordinate.latitude
    userLongitude = location.coordinate.longitude
    print("Hello I'm here! \(location)")
  }
}

每当我回到我的ContentView并尝试阅读纬度/经度时,它只会显示为 0.0。但如果我在体内输出它们,值就会正确显示。

struct ContentView: View {
    @State private var times = prayerTimes()
 @ObservedObject var locationViewModel = LocationViewModel()
    var body: some View {
        NavigationView {
            PrayerTimeView(times: $times)
                .navigationBarTitle(Text("Prayer Times"))
        }
    }

    static func prayerTimes() -> PrayerTimes? {
        let cal = Calendar(identifier: Calendar.Identifier.gregorian)
        let date = cal.dateComponents([.year, .month, .day], from: Date())
        let coordinates = Coordinates(latitude: locationViewMode.userLatitude, longitude: locationViewMode.userLongitude)
        var params = CalculationMethod.moonsightingCommittee.params
        params.madhab = .hanafi
        return PrayerTimes(coordinates: coordinates, date: date, calculationParameters: params)
    }
}
4

1 回答 1

0

prayerTimes()初始化视图时只调用一次。你为什么不把你的 ViewModeltimes作为一个@Published。当位置更改时,只需更新该值。

PrayerTimeView(times: $viewmodel.times)
                .navigationBarTitle(Text("Prayer Times"))
于 2020-11-22T05:18:13.857 回答