SwiftUI trying to expand my sheet when tapping anywhere on it (similar to Maps app)

144 Views Asked by At

I’m trying to make my sheet expand when tapping anywhere on it but this implementation seems to completely override normal tap gesture and the navigation links inside the sheet only respond to a long tap now. How to expand the sheet without blocking normal tap gesture ?

import SwiftUI


struct ExampleSheet: View {
    let heights = stride(from: 0.1, through: 1.0, by: 0.25).map { PresentationDetent.fraction($0) }
    @State private var height = PresentationDetent.fraction(0.15)
   
    let players = [
        "Roy Kent",
        "Richard Montlaur",
        "Dani Rojas",
        "Jamie Tartt",
    ]
    
    var body: some View {
        VStack{
            NavigationView {
                List(players, id: \.self) { player in
                    NavigationLink(destination: PlayerView(name: player)) {
                        Text(player)
                    }
                }            
            }
            .presentationDetents([.fraction(0.15), .medium, .large], selection: $height)
            .interactiveDismissDisabled()
        }.onTapGesture {
           height = PresentationDetent.large // how to expand the sheet without blocking normal tap gesture ?
        }
    }
}
struct MyMapView: View {
    @State private var showingSheet = true
    var body: some View {
        Button("Show Sheet") {
            showingSheet.toggle()
        }
        Spacer()
        .sheet(isPresented: $showingSheet, content: {
            ExampleSheet()
        })
    } 
}

struct PlayerView: View {
    let name: String
    var body: some View {
        Text("Selected player: \(name)")
            .font(.largeTitle)
    }
}
1

There are 1 best solutions below

0
On

You could set up a simultaneous tap gesture so that the button will also get triggered on a tap

struct ExampleSheet: View {
    let heights = stride(from: 0.1, through: 1.0, by: 0.25).map { PresentationDetent.fraction($0) }
    @State private var height = PresentationDetent.fraction(0.15)
   
    let players = [
        "Roy Kent",
        "Richard Montlaur",
        "Dani Rojas",
        "Jamie Tartt",
    ]
    
    var body: some View {
        VStack{
            NavigationView {
                List(players, id: \.self) { player in
                    NavigationLink(destination: PlayerView(name: player)) {
                        Text(player)
                    }
                }            
            }
            .presentationDetents([.fraction(0.15), .medium, .large], selection: $height)
            .interactiveDismissDisabled()
        }
        .simultaneousGesture(
            TapGesture().onEnded { _ in
                height = PresentationDetent.large // how to expand the sheet without blocking normal tap gesture ?
            }
        )
    }
}