更改ViewModel中的位置值时更新SwiftUI视图

时间:2020-04-06 10:31:31

标签: swift swiftui

嗨,

我有一个应用程序,我想在其中获取用户的当前位置,以自动完成TextField中的位置,如果不是正确的位置,可以让用户编写所需的位置。

我尝试过的事情:

final class ViewModel: NSObject, ObservableObject, CLLocationManagerDelegate {
      var locationManager: CLLocationManager

      public let objectWillChange = PassthroughSubject<String,Never>()

      public private(set) var latestLocation: String = "" {
            willSet {
                objectWillChange.send(newValue)
            }
       }

       override init() {
         locationManager = CLLocationManager()
         super.init()
         locationManager.delegate = self
         locationManager.desiredAccuracy = kCLLocationAccuracyBest
         locationManager.requestWhenInUseAuthorization()

         if CLLocationManager.locationServicesEnabled(){
             locationManager.startUpdatingLocation()
          }
        }   

       func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
          let userLocation :CLLocation = locations[0] as CLLocation

           let geocoder = CLGeocoder()
           geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
                 if (error != nil){
                  print("error in reverseGeocode")
         }

          let placemark = placemarks! as [CLPlacemark]

          if placemark.count>0 {
            let placemark = placemarks![0]

            self.latestLocation = "\(String(describing: placemark.locality))"
            }
        }   
}

这是SwiftUI文件:

struct FormView: View {
      @ObservedObject var viewModel: ViewModel = ViewModel()

          @State private var location: String = ""

          var body: some View {
               return Form {

                     TextField(title: $location) 
                           .onReceive(self.viewModel.objectWillChange) { value in
                               self.location = value
                           }                    
               }
I ALSO TRYIED THIS:
    //        .onReceive(self.viewModel.$latestLocation) { value in
    //            self.location = value
                  }
    }

我看到的是该位置首先在View上更新,然后在ViewModel中更新,因此我的TextField文本始终为空。

1 个答案:

答案 0 :(得分:0)

如何使用

TextField(location, text: $location)

TextField是否仍然为空?