我对可观察对象还有另一个问题。
在“位置 1”行的视图中,我有用于编辑地址的文本视图(并将其保存到必须在视图中显示的状态属性“文本”中)。
状态变量“text”必须从类 LocationObserver 属性“currentAddress”初始化。我只是试图设置视图的初始化有人可以帮助我吗?
提前致谢!
最好的
德拉甘
The View
struct PickFoto: View {
@ObservedObject var observeLocation = LocationObserver.shared()!
@State private var address = LocationObserver.shared()?.currentAddress ?? " "
...
TextView(text: $text, isEditing: $isEditing) // Position 1
Text("current Address (observeLocation): \(observeLocation.currentAddress)") // Position 2
...
}
The Shared Object
class LocationObserver: NSObject, CLLocationManagerDelegate, ObservableObject {
// This published property value has to be the initial value
// for the TextView (the property $text. how to to this??)
@Published var currentAddress = " "
static var instance: LocationObserver?
var locationManager = CLLocationManager()
var defaultLocation = CLLocation(latitude: 52.516861, longitude:13.356796)
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let currentLocation = locations.last?.coordinate
convertGPSToAdress(coordinates: locations.last ?? defaultLocation,
completion: { (retStr: String) in
self.currentAddress = retStr // set the @Published property
print("currentAddress in EscapingClosure: \(self.currentAddress)")
//everything is fine
}
)
}
func convertGPSToAdress(coordinates: CLLocation,
completion: @escaping(String) -> ()) -> () {
let address = CLGeocoder.init()
address.reverseGeocodeLocation(coordinates) { (places, error) in
if error == nil{
if places != nil {
let place = places?.first
completion(formatAddressString(place: place!)) // returns a formatted string address
}
}
}
}
....
}