Playback speed
×
Share post
Share post at current time
0:00
/
0:00
Transcript

SwiftUI FYI #14 - Sheet Presentation Detents

Customize sheet sizes using Presentation Detents #SwiftUI

Hey! 👋

Let’s explore how to customize sheet sizes in SwiftUI using the Presentation Detents feature.

We have four main approaches to achieve this:

  1. Predefined Detents: SwiftUI offers predefined detents, such as .medium and .large, which provide a convenient way to set specific sheet sizes.

  2. Fractions: Another approach is to specify a fraction of the available height using a value between 0 and 1.0. This allows you to customize the sheet size to a specific percentage of the screen.

  3. Fixed Height: If you prefer a fixed sheet size, you can use the fixed height option. This method ensures that the sheet remains the same size regardless of the screen size.

  4. Custom: For more advanced customization, you can create your own type that conforms to the CustomPresentationDetent protocol. This allows you to override the height(in:) method to set your desired sheet size.

In today’s example, I’ll demonstrate the first three approaches.

Tip: You can define multiple detents. The default value will be the first one you specify. By providing more than one value, you enable the user to resize the sheet.

🚨 Full code below and also on Github

🤝 Find more about me on saidmarouf.com. I’m also on XThreads, and LinkedIn

Thanks for reading Your Weekly SwiftUI FYI 💡! Subscribe for free to receive new posts and support my work.


import SwiftUI

struct SheetsExampleView: View {
    
    @State var isPresented: Bool = false
    
    var body: some View {
        
        VStack {
            Button {
                isPresented.toggle()
            } label: {
                Text("Show Sheet").font(.largeTitle)
            }.buttonStyle(.borderedProminent)
        }
        .sheet(isPresented: $isPresented) {
            MySheetView()
        }
    }
}

struct MySheetView: View {
    
    var body: some View {
        VStack {
            Text("Hello! I am a sheet")
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .font(.largeTitle)
                .background(.purple)
        }
        .presentationDetents([.medium, .large])
        //.presentationDetents([.fraction(0.5), .large])
        //.presentationDetents([.fraction(0.3), .fraction(0.7)])
        //.presentationDetents([.height(200)])
    }
}

#Preview {
    SheetsExampleView()
}

Discussion about this podcast

Your Weekly SwiftUI FYI 💡
Your Weekly SwiftUI FYI 💡