swiftswiftuiapple-watchwatchoswatchos-10

How to hide the dismiss button (x) when presenting a .sheet in watchOS?


I use a .sheet to present a workout UI during a workout. WatchOS 10 seems to have added a dismiss button ("X") in the top left corner out of the box to a view presented via .sheet. How can I hide it? It was suggested to use a .cancellationAction with an empty view to hide it but this doesn't work. Any other ways I can remove the dismiss button?

struct ContentView: View {
    
    @State var isShowingSheet: Bool = false
    
    var body: some View {
        NavigationStack {
        VStack {
            Button {
                isShowingSheet = true
            } label: {
                Text("Show Sheet")
            }
            
        }
    }
        .padding()
        .sheet(isPresented: $isShowingSheet, content: {
            //NavigationStack {  //adding doesn't change 
                VStack {
                    Text("Sheet Content")
                    
                }
          //  }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.red.gradient)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button(action: {
                        print("button tapped")
                    }, label: {
                        EmptyView() //Doesn't hide dismiss button
                    })
                }
            }
        })
    }
}

#Preview {
    ContentView()
}

Solution

  • You can achieve it by introducing the NavigationView and then you can hide the navigation bar with the "X" button by using .toolbar(.hidden, for: .navigationBar):

            .sheet(isPresented: $isShowingSheet, content: {
                NavigationView { // <-- 1
                    VStack {
                        Text("Sheet Content")
                    }
                }
                .toolbar(.hidden, for: .navigationBar) // <-- 2
                // .frame(..)