SwiftUI - Make List Divider Line Expand To Touch Screen Edges

Viewed 635

I am working with lists in SwiftUI. I cannot figure out how to make the line separator go edge to edge. I have tried .edgesIgnoringSafeArea, but that does not seem to do the trick. See image below:

enter image description here

Notice how the list lines touch the right edge, but not the left.

1 Answers

It doesn't seem there's proper solution to control the separator in particular, so you have to have your own workaround.

I would suggest to play with the EdgeInsets to expand the row to reach edges, so the separator.

Then you can add the padding you want to row's content.

List(0..<10) { _ in
     HStack {
          Text("title")
           Spacer()
     }.background(Color.gray)
      .padding(.horizontal, 20)
 }.padding(EdgeInsets(top: 0, leading: -20, bottom: 0, trailing: -20))

And the final result would be something like this:

And the final result would be something like this:

You can also simplify it further by replacing

.padding(EdgeInsets(top: 0, leading: -20, bottom: 0, trailing: -20))

with

.padding(.horizontal, -20)

You could have different padding/Inset for each row, here's a code snippet from Apple's documentation for listRowInsets

struct ContentView: View {
    enum Flavor: String, CaseIterable, Identifiable {
        var id: String { self.rawValue }
        case vanilla, chocolate, strawberry
    }

    var body: some View {
        List {
            ForEach(Flavor.allCases) {
                Text($0.rawValue)
                    .listRowInsets(.init(top: 0,
                                         leading: 25,
                                         bottom: 0,
                                         trailing: 0))
            }
        }
    }
}
Related