SwiftUI update Map region causes warning about Modifying state.

I have a project that uses the new SwiftUI Map in iOS 14

I want to be able to update the location of the Map centre dynamically.

When you tap the Zoom button and then the Location Button the Map works fine and re-centers to London.

However if you just tap the location button it re-centers to London but throws a warning about the ViewState.

I am at a loss for what is causing this issue and how to fix it.




    @State private var region = MKCoordinateRegion(

        center: CLLocationCoordinate2D(

            latitude: 25.7617,

            longitude: 80.1918

        ),

        span: MKCoordinateSpan(

            latitudeDelta: 10,

            longitudeDelta: 10

        )

    )



    var body: some View {

        VStack {

            Map(coordinateRegion: $region)



            Button("zoom") {

                withAnimation {

                    region.span = MKCoordinateSpan(

                        latitudeDelta: 100,

                        longitudeDelta: 100

                    )

                }

            }



            Button(action: {

                withAnimation {

                    region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))



                }

            }) {

                Image(systemName: "location.fill")

                    .frame(width: 44, height: 44, alignment: .center)

                    .foregroundColor(.black)

                .background(Color(.white))

            }.buttonStyle(PlainButtonStyle())

            .clipShape(Circle())

            .shadow(color: .black.opacity(0.5), radius: 1.0, x: 0.0, y: 2.0)

        }

    }

}
Post not yet marked as solved Up vote post of Victvs Down vote post of Victvs
1.1k views