How to prevent TextField from disappearing in SwiftUI List?

There's a nasty SwiftUI bug in which a

TextField
disappears if placed in a
HStack
within a
List.


List {
ForEach(0...200, id: \.self) { index in
HStack {
Text("Text \(index)")
TextField("Test", text: .constant("TextField \(index)"))
}
}
}


- Screenshot: https://i.stack.imgur.com/HARDF.png

- Video: https://recordit.co/X12uGct7gD


This happens when

TextField
is placed within a
HStack / VStack / ZStack / .overlay() / .background()
. It does not happen when
TextField
is the only child of
ForEach
.


I have filed a bug (FB7500885) but I'm looking for ideas from the community to work around it. Here is what I've tried so far:

  • Setting an explicit
    .frame()
    on
    TextField
  • Setting
    .fixedSized()
    on
    TextField
  • Using a
    UITextField
    wrapped in a
    UIViewConvertible
    , with or without layout constraints


Is there anything else I could try?

Replies

Fyi this is what fixed it: https://stackoverflow.com/a/59429857/646960


TextField("Test", text: .constant("TextField \(index)"))

    .id(index)


Not sure exactly why `id` is required here.

Confirm, it works (in SwiftUI simulator on Mojave)


Doc stats about .id()

Generates a uniquely identified view that can be inserted or removed.


So, that has probably to deal with how List manages the dequeue of cells.

Whatever the reason, that shows Swift UI still has some rough edges… 😉


Not sure exactly why `id` is required here.

This should shed some light on .id()

h ttps://www.raywenderlich.com/5824937-swiftui-tutorial-navigation

Thank you! This was driving me insane. Setting the `id` worked.

Looks like this was fixed in iOS 14 b1/Xcode 12 b1!