下面的swiftUI代码在iOS13上可以正常工作,但是在iOS14上进行测试时,由于试图显示模式表时强制展开的 optional 引起的致命错误。据我所知,工作表绝不要尝试为selectedModel呈现nil值,因为showingDetails仅在分配selectedModel后才变为true?

struct SpeakerBrandMenu: View {
    var filteredSpeakers: [Speaker] {
        // An array of Speaker objects
        }

    @State var selectedModel: Speaker?
    @State private var showingDetails = false

    var body: some View {
        List{
        ForEach(filteredSpeakers) { speaker in
            HStack {
                Button(action: {
                    self.selectedModel = speaker
                    self.showingDetails = true
                }) {
                    SpeakerModelRow(speaker: speaker).contentShape(Rectangle())
                }
                .buttonStyle(PlainButtonStyle())

                Spacer()

                Button(
                //unrelated
                ).padding(5)
              }
            }
        } .sheet(isPresented: self.$showingDetails) { SpeakerDetailView(speaker: self.selectedModel!, showSheet: self.$showingDetails).environmentObject(self.favoriteSpeakers).environmentObject(self.settings)}

          .navigationBarTitle(Text(brand), displayMode: .inline)
    }
}
有趣的是,如果我将其解压缩为speaker: self.selectedModel ?? filteredSpeakers[0],其行为将完全符合预期:第一次按下任何菜单项时,第一个项将传递给工作表,但是在解散工作表并选择另一个项时,每次都会显示正确的项。因此,好像分配selectedModel的按钮试图在分配时间之前显示工作表。

最佳答案

在iOS 14中,现在似乎已经预先创建了sheet(isPresented:content:),因此对selectedModel所做的任何更改都将被忽略。
尝试改用sheet(item:content:):

var body: some View {
    List {
        ...
    }
    .sheet(item: self.$selectedModel) {
        SpeakerDetailView(speaker: $0)
    }
}
并使用@Environment(\.presentationMode)关闭工作表:
struct SpeakerDetailView: View {
    @Environment(\.presentationMode) private var presentationMode
    var speaker: Speaker

    var body: some View {
        Text("Speaker view")
            .onTapGesture {
                presentationMode.wrappedValue.dismiss()
            }
    }
}

08-06 12:42