有沒有辦法更新 MapView 作業表/NavigationLink 的 MKCoordinateRegion 出現?
我有一個視圖用于輸入一些資料以從街道地址創建經度/緯度組合:
創建.swift:
@State var longitude:Double = -122.677579; // Default longitude
@State var latitude:Double = 45.515519; // Default latitude
@State var streetAddress:String = ""; // Empty string
@State private var isShowing = false;
var body:some View {
VStack {
/* Take in the street address string via TextField */
Button(action:{validate()}, label:"Next")
}
.sheet(isPresented:$isShowing) {
LocationPicker(longitude:self.longitude, latitude:self.latitude)
};
}
func validate() {
var isValid:Bool = false;
/*
1. convert the street address to longitude and latitude
2. store long/lat in self.longitude, self.latitude
3. set isValid to true
*/
isShowing = true;
}
流量:
- 接受用戶的街道地址
- 單擊“下一步”按鈕通過將街道地址轉換為經度/緯度來驗證街道地址
- 這些經度和緯度值存盤在狀態變數中
- isShowing 設定為 true,調出
.sheet包含LocationPicker視圖的 .
位置選擇器.swift:
struct LocationPicker: View {
@State var latitude:Double;
@State var longitude:Double;
var span:MKCoordinateSpan = MKCoordinateSpan(
latitudeDelta: 0.009,
longitudeDelta: 0.009
)
@State var region:MKCoordinateRegion;
init(latitude:Double, longitude:Double) {
_latitude = State(initialValue: latitude)
_longitude = State(initialValue: longitude)
_region = State(initialValue :MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: latitude, longitude: longitude),
span: self.span
))
}
var body:some View {
Map(coordinateRegion: $region,
showsUserLocation: false
)
/* ... */
}
}
我對這個配置的問題是當視圖被渲染時.sheet's LocationPickerin被渲染。因此,當我將經度/緯度狀態傳遞給作業表時,會傳遞默認值,并且地圖打開時出現的中心點是默認坐標,而不是由in生成的坐標。Create.swiftCreate.swiftLocationPickerstreetAddressvalidate()
我嘗試同時使用 invisibleNavigationLink和.sheetin Create.swift,但兩者都與父級同時渲染。我嘗試使用@Binding雙打LocationPicker.swift:
struct LocationPicker: View {
@Binding var latitude:Double;
@Binding var longitude:Double;
var span:MKCoordinateSpan = MKCoordinateSpan(
latitudeDelta: 0.009,
longitudeDelta: 0.009
)
@State var region:MKCoordinateRegion;
init(latitude:Binding<Double>, longitude:Binding<Double>) {
_latitude = latitude
_longitude = longitude
_region = State(initialValue :MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: latitude, longitude: longitude),
span: self.span
))
}
var body:some View {
Map(coordinateRegion: $region,
showsUserLocation: false
)
/* ... */
}
但是,CLLocationCoordinate2D不接受Binding<Double>作為緯度或經度的資料型別。
uj5u.com熱心網友回復:
將 a 傳遞Binding給 init 時,如果需要使用 中包含的值,則Binding必須使用.wrappedValue來訪問基礎值。在這種情況下,您傳入兩個Binding<Double>并嘗試使用它們來創建一個CLLocationCoordinate2D,因此初始化程式必須如下所示:
init(latitude:Binding<Double>, longitude:Binding<Double>) {
// Binding
_latitude = latitude
// Binding
_longitude = longitude
_region = State(initialValue :MKCoordinateRegion(
// not Bindings
center: CLLocationCoordinate2D(latitude: latitude.wrappedValue, longitude: longitude.wrappedValue),
span: self.span
))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464489.html
