Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyboard is immediately hidden when focus TextField in LazyVStack (SwiftUI)

I have a stack of cards, each card having a TextField, when focus a text field positioned at the bottom of the screen (on the area where the keyboard will appear) the card disappears, thus the keyboard disappears as well. I expect that the field is focused and scrolled automatically to the visible area. I found that the "Submit" button I have fixed at the bottom of the screen is causing the issue, so it works fine if I remove it. Another solution would be to use VStack instead of LazyVStack but I really need this Lazy behaviour since there can be lots of cards

struct ContentView: View {

   @State private var text: String = ""

   var body: some View {
       VStack {
           ScrollView {
               LazyVStack {
                   ForEach(0..<200, id: \.self) { _ in
                       CardView()
                   }
               }
           }
           Button("Submit") { }
               .frame(maxWidth: .infinity)
               .background(Color.white)
            
       }.background(Color.secondary)
   }
}

struct CardView: View {

   @State private var text: String = ""

   var body: some View {
       TextField("text", text: $text)
           .frame(height: 50, alignment: .leading)
           .background(Color.white)
   }
}

enter image description here

like image 731
Sorin Lica Avatar asked Jan 19 '26 12:01

Sorin Lica


1 Answers

You can try putting the button inside the section footer and make the footer pinned like this:

var body: some View {
   ScrollView {
       LazyVStack(pinnedViews: .sectionFooters) {
           Section {
               ForEach(0..<200, id: \.self) { _ in
                   CardView()
               }
           } footer: {
              Button("Submit") { }
                  .frame(maxWidth: .infinity)
                  .background(Color.white)
           }
       }
   }
   .background(Color.secondary)
}

It seems to solve the issue with the disappearing keyboard (at least in the iOS 17.4 simulator), but introduces another problem where the scroll position of the focused text field gets calculated incorrectly and it gets overlapped by the footer. Not sure if it's helpful, but may be you can take it from here.

like image 66
Vadim Belyaev Avatar answered Jan 22 '26 06:01

Vadim Belyaev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!