Reputation: 6306
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:
When I remove the Text("km")
line however, everything works as expected:
List {
HStack {
TextField("Some field", text: .constant("Hello"))
}
Text("Hello")
}
I have no idea what's going on here. Any suggestions?
Upvotes: 0
Views: 59
Reputation: 119917
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")
}
Upvotes: 1
Reputation: 26
SwiftUI's default separator placement relies on the layout information of the direct children of the List. When you only have HStack views, the layout system might not have enough information to reliably determine where to draw the separator, especially if the HStack content doesn't fully span the width of the list row.
you can get the same behaviour using this code
let items = [
Item(text: "Hello", unit: "km"),
Item(text: "World", unit: "m"),
Item(text: "Test", unit: "cm")
]
var body: some View {
ScrollView {
VStack {
ForEach(items) { item in
ItemRow(item: item)
}
}
.padding()
}
}
struct Item: Identifiable {
let id = UUID()
let text: String
let unit: String
}
struct ItemRow: View {
let item: Item
var body: some View {
VStack {
HStack {
TextField("Some field", text: .constant(item.text))
Text(item.unit)
}
Divider()
}
}
}
Upvotes: 0