Данные, перенесенные в следующее представление, противоречивы.IOS

Программируем под IOS
Ответить
Гость
 Данные, перенесенные в следующее представление, противоречивы.

Сообщение Гость »


I'm having troubles pushing data to the next view in SwiftUI. The first data pushed is correct for one annotation , but all the others either push nothing or the wrong data :-(. Looks like the declaration isn't made in the right place, but cannot find out where.

Here's my MapView :

import MapKit import SwiftUI import CoreLocation struct MapViewJS: View { @State private var locations: [Location] = [] private var viewModel: MapViewModel = MapViewModel() @State private var isAnnotationTapped = false @State var selected: Location? @State private var isDetailViewPresented = false @State private var valueToPass = "Test value" @State private var coordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 50.724286, longitude: 0.181787), span: MKCoordinateSpan(latitudeDelta: 2.5, longitudeDelta: 2.5)) var body: some View { Map(coordinateRegion: viewModel.binding,annotationItems: locations) { location in MapAnnotation( coordinate: CLLocationCoordinate2D( latitude: location.latitude, longitude: location.longitude ) ) { VStack { Text("") Image(systemName: "location.north.line") .font(.system(size: 20)) .foregroundColor(.indigo) .scaledToFit() .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/) .frame(width: 100, height: 25) .clipShape(Circle()) .overlay( Circle().stroke(Color.white, lineWidth: 25/10)) .shadow(radius: 10) .onTapGesture { if let currentSelected = selected, currentSelected == location { selected = nil } else { selected = location } } Button(action: { isDetailViewPresented.toggle() }) { Text("\(location.name) \n \(location.latitude)") } .sheet(isPresented: $isDetailViewPresented) { DetailView(passedValue: Binding( get: { location.name }, set: { passedValue in isDetailViewPresented = false } )) } .opacity(location.ident == selected?.ident ? 1 : 0) } //vstack } } .edgesIgnoringSafeArea(.all) .onAppear(perform: { viewModel.checkIfLocationIsEnabled();readFile() }) } private func readFile() { if let url = Bundle.main.url(forResource: "events", withExtension: "json"), let data = try? Data(contentsOf: url) { let decoder = JSONDecoder() if let jsonData = try? decoder.decode(JSONData.self, from: data) { self.locations = jsonData.locations } } } } struct DetailView: View { //should be webview @Binding var passedValue: String var body: some View { VStack { Text("Passed Value: \(passedValue)") } } } struct JSONData: Decodable { let locations: [Location] } struct Location: Decodable, Identifiable, Equatable { let id: Int let name: String let latitude: Double let longitude: Double let ident = UUID() } final class MapViewModel: NSObject, ObservableObject, CLLocationManagerDelegate { var locationManager: CLLocationManager? @Published var mapRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 50.724286, longitude: 0.181787), span: MKCoordinateSpan(latitudeDelta: 2.5, longitudeDelta: 2.5)) var binding: Binding { Binding { self.mapRegion } set: { newRegion in self.mapRegion = newRegion } } func checkIfLocationIsEnabled() { DispatchQueue.global(qos: .background).async { if CLLocationManager.locationServicesEnabled() { DispatchQueue.main.async { self.locationManager = CLLocationManager() self.locationManager?.desiredAccuracy = kCLLocationAccuracyBest self.locationManager?.delegate = self } } else { DispatchQueue.main.async { print("Location services are off_checkIfLocationIsEnabled") } } } } func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { switch manager.authorizationStatus { case .notDetermined: manager.requestWhenInUseAuthorization() case .restricted: print("Location is restricted_locationManagerDidChangeAuthorization") case .denied: print("Location permission denied_locationManagerDidChangeAuthorization") case .authorizedAlways, .authorizedWhenInUse: checkLocationAuthorization() default: break } } private func checkLocationAuthorization() { guard let location = locationManager else { return } switch location.authorizationStatus { case .notDetermined: print("Location authorization_checkLocationAuthorization") case .restricted: print("Location is restricted_checkLocationAuthorization") case .denied: print("Location permission denied_checkLocationAuthorization") case .authorizedAlways, .authorizedWhenInUse: DispatchQueue.main.async { if let location = location.location { self.mapRegion = MKCoordinateRegion(center: location.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)) } } default: break } } } struct MapViewJS_Previews: PreviewProvider { static var previews: some View { MapViewJS() } } Any help would be greatly appreciated.


Источник: https://stackoverflow.com/questions/781 ... consistent
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»