TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SwiftUI Sheet Animation Issue with Non-Default Background Colors

Forums > SwiftUI

I'm working on a SwiftUI project where I use a .sheet modifier to present a bottom drawer with two detent sizes: .medium and .large. The drawer contains a button that toggles its size between these two states. This part works as expected. However, I'm facing an animation issue when I set a non-default background color to the sheet.

Here's the simplified code for context:

struct ContentView: View {

    @State private var selectedDetent: PresentationDetent = .medium

    var body: some View {
        VStack {}
            .sheet(isPresented: .constant(true)) {
                Button("Press Me") {
                    selectedDetent = selectedDetent == .medium ? .large : .medium
                }
                .presentationBackground(.gray)
                .presentationDetents([.medium, .large], selection: $selectedDetent)
            }
    }
}

The issue arises when I try to set a background color using .presentationBackground(.gray) (or any color, even white). Instead of the expected behavior when pressing the button (where the upper part of the sheet closes, and the bottom part stays attached to the screen bottom), the sheet momentarily turns into a square in the middle of the screen before moving down to the .medium position.

As soon as I remove the .presentationBackground(.gray) line, it works as expected:

I tried several approaches, such as:

  • Using a custom background view.
  • Explicitly specifying animations.
  • Adjusting view hierarchy and layering.

Unfortunately, none of these solutions worked. The issue persists with any color. It seems like a bug or limitation in SwiftUI's handling of sheet animations with custom backgrounds.

Has anyone else encountered this issue, or does anyone have a workaround or solution?

2      

This appears to be a bug. The user Benzy Neez gave me a workaround on GitHub:

You can use a custom background that overflows the bottom of the screen by a sufficient amount to fill the gap that is seen when the size changes:

.presentationBackground {
    Color.gray
        .padding(.bottom, -1000)
}

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.