3

For some reason, my selectedTask State is Empty when presenting the Sheet, even if I set it on the onTapGesture. What I'm I missing?

struct TasksTabView: View {

    @State private var showComputedTaskSheet: Bool = false
    @State var selectedTask: OrderTaskCheck?

    var body: some View {
        VStack(alignment: .leading) {
            List {
                ForEach(Array(tasks.enumerated()), id:\.1.title) { (index, task) in
                    VStack(alignment: .leading, spacing: 40) {
                        HStack(spacing: 20) {
                            PillForRow(index: index, task: task)
                        }.padding(.bottom, 30)
                    }.onTapGesture {
                        // Where I'm setting selectedTask
                        self.selectedTask = task
                        self.showComputedTaskSheet.toggle()
                    }
                }
            }
        }.listStyle(SidebarListStyle())
    }
    .sheet(isPresented: $showComputedTaskSheet) {
        // self.selectedTask is returns nil
        showScreen(task: self.selectedTask!)
    }
    .onAppear {
        UITableView.appearance().backgroundColor = .white
    }
}
John
  • 799
  • 6
  • 22

1 Answers1

4

Since I have no access to your full project this example can help you to get the idea, you can use .sheet() with item initializer like aheze said.

The advantage is here you pass optional to input item and you receive unwrapped safe value to work!

struct ContentView: View {

    @State private var customValue: CustomValue?
    
    var body: some View {

        Button("Show the Sheet View") { customValue = CustomValue(description: "Hello, World!") }
            .sheet(item: $customValue){ item in sheetView(item: item) }
 
    }
    
    func sheetView(item: CustomValue) -> some View {
        
        return VStack {
            
            Text(item.description)
            
            Button("Close the Sheet View") { customValue = nil }.padding()
            
        }
    }
    
}

struct CustomValue: Identifiable {
    let id: UUID = UUID()
    var description: String
}
ios coder
  • 1
  • 4
  • 31
  • 91