Can not pass varible to region in MKCoordinateRegion in swift

238 Views Asked by At

I need a variable map for each page. "number" chooses the element from the array of data that has been collected from JSON. The var "number" gives the error in "@State private var region".

The error is: Cannot use instance member 'number' within property initializer; property initializers run before 'self' is available.

Link of the project: https://github.com/parsadevuk/Swift-LondonParks/blob/main/LondonParks/Views%20Group/MapView.swift

import SwiftUI
import MapKit
import CoreLocationUI

struct MapView: View {

    var number : Int!
    init(number : Int!) {
        self.number = number ?? 0
    }

    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D( latitude: parksData[number].locationCoordinate.latitude, longitude: parksData[number].locationCoordinate.longitude), span: MKCoordinateSpan(latitudeDelta: 0.03, longitudeDelta: 0.03))

    var body: some View {
        VStack{
        Map(coordinateRegion: $region)
            .frame(width: 400, height: 400, alignment: .top)
        Image(parksData[number].imageName)
            .frame(width: 200, height: 200, alignment: .bottom)
        }
    }

    private func setRegion(_ coordinate: CLLocationCoordinate2D) {
        region = MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2))
    }
}

struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView(number: 1)
    }
}
0

There are 0 best solutions below