0

我有一个显示数组的表单。每行都是我要打开全屏封面的按钮。

问题是,第一次触发按钮并显示工作表时,本例中的对象city为 nil。

当使用工作表而不是 fullscreenCover 或列表或 vstack 而不是表单时,也会发生同样的情况。

在此处输入图像描述

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)
    }
}

我非常感谢提示为什么第一次调用该对象为零。

谢谢你。

4

0 回答 0