从观察到的对象初始化状态变量



我对可观察对象有另一个问题。

在"位置1"行的视图中,我有用于编辑地址的文本视图(并将其保存到状态属性"text"中,该属性必须显示在视图中(
必须从类LocationObserver属性"currentAddress"初始化状态变量"text"。我只是试图设置视图的初始化有人能帮我吗?

提前感谢!

最佳

德拉甘


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 
}
}
}
}
....
}

尝试以下操作(代码快照不可测试-所以只是草稿(

struct PickFoto: View {
@ObservedObject var observeLocation = LocationObserver.shared()!
@State private var address: String
init() {
_address = State<String>(initialValue: LocationObserver.shared()?.currentAddress ?? " ")
}
...

更新:将私有address状态与外部同步

var body: some View {
...
TextView(text: $text, isEditing: $isEditing) 
.onReceive(observeLocation.$currentAddress) { newAddress in
self.address = newAddress
}
...
}

最新更新