Search code examples
swiftuiswiftui-list

Why does my list row separator disappear?


This is in Xcode 16.2 with the iOS 18 SDK, build target iOS 17.

I have some very simple code:

List {
    HStack {
        TextField("Some field", text: .constant("Hello"))
        Text("km")
    }
    Text("Hello")
}

When I run it the separator between the 2 list rows disappears beneath the TextField part:

disappearing separator

When I remove the Text("km") line however, everything works as expected:

List {
    HStack {
        TextField("Some field", text: .constant("Hello"))
    }
    Text("Hello")
}

Correct behaviour

I have no idea what's going on here. Any suggestions?


Solution

  • SwiftUI attempts to automatically align elements in a row with the separator, but it may not always succeed.

    You can manually specify exactly which element you want the separator to align with using the alignmentGuide modifier like this:

    List {
        HStack {
            TextField("Some field", text: .constant("Hello"))
                .alignmentGuide(.listRowSeparatorLeading) { $0[.leading] } // 👈 Telling that separators should be aligned with this component here
    
            Text("km")
        }
    
        Text("Hello")
    }