iosswiftswiftui

SwiftUI Keyboard Animation Bug When Presented Inside Sheet


This seems to be a bug in SwiftUI when there is a text field inside of a sheet that has a presentationBackground set along with a presentationDetent of .medium.

When the keyboard is dismissed, there is a large gap that appears at the bottom as the presentation background recomputes its position relative to the keyboard.

Screen capture here: https://imgur.com/a/KTglA1U

enter image description here

Using .ignoresSafeArea() or .edgesIgnoringSafeArea() don't seem to do anything.

If I remove the presentationBackground or .medium detent, the issue goes away.

Any thoughts or advice on how to fix?

Thanks in advance

This is on XCode 16.

import SwiftUI

struct ContentView: View {
  @State var isPresented = false

  var body: some View {
    VStack {
      Image(systemName: "globe")
        .imageScale(.large)
        .foregroundStyle(.tint)

      Button("Present sheet") {
        self.isPresented.toggle()
      }
    }
    .sheet(isPresented: $isPresented) {
      ScrollView {
        TextField("Enter text here", text: .constant(""))
          .padding()
    
      }
      .ignoresSafeArea()
      .scrollDismissesKeyboard(.interactively)
      .presentationDetents([.medium, .large])
      .presentationBackground(Color.red.opacity(0.75))
    }
    .padding()
  }
}

Solution

  • The workaround described in the answer to SwiftUI Sheet Animation Issue with Non-Default Background Colors seems to help here too (it was my answer).

    In this case, the negative padding probably only needs to exceed the size of the bottom safe area insets, it doesn't need to be much more.

    ScrollView {
        // ...
    }
    .scrollDismissesKeyboard(.interactively)
    .presentationDetents([.medium, .large])
    .presentationBackground {
        Color.red.opacity(0.75)
            .padding(.bottom, -100)
    }