I am having a Form where an array is shown. Each row is a button where I want to open a fullscreenCover.

The issue is, for the very first time a button is triggered and the sheet is shown, the object in this case city is nil.

The same happens when using a sheet instead of the fullscreenCover or a list or vstack instead of a form.

enter image description here

import SwiftUI

struct City: Identifiable {
    let id = UUID()
    let name: String
    let population: Int
}

struct ContentView: View {
    let cities = [City(name: "Munich", population: 1500000), City(name: "San Diego", population: 1400000), City(name: "Sydney", population: 5300000), City(name: "London", population: 8900000)]

    @State var showFullscreenCover = false
    @State var selectedCity: City?

    var body: some View {
        NavigationView {
            Form {
                ForEach(cities) { city in
                    Button(city.name) {
                        selectedCity = city
                        showFullscreenCover.toggle()
                    }
                }
            }
            .fullScreenCover(isPresented: $showFullscreenCover, onDismiss: {
                selectedCity = nil
            }) {
                CityView(city: selectedCity)
            }
            .navigationTitle("City Population")
        }
    }
}

struct CityView: View {
    var city: City?

    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        if let city = city {
            NavigationView {
                VStack {
                    Text("Population")
                    Text("\(city.population)")
                }
                .navigationTitle(city.name)
                .navigationBarItems(leading:
                    Button("Cancel") {
                        presentationMode.wrappedValue.dismiss()
                    }
                )
            }
        } else {
            NavigationView {
                Text("City object is nil")
                    .navigationBarItems(leading:
                        Button("Cancel") {
                            presentationMode.wrappedValue.dismiss()
                        }
                    )
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .previewDevice("iPhone 12 Pro")
            .colorScheme(.dark)
    }
}

I would very much appreciate a hint why the object is nil for the first call.

Thank you.

0

There are 0 answers