How can I create a SwiftUI list with separated members, without using Section

Viewed 62

How can I, without using Section, achieve a list that looks like this:

List with separated members --> This list has separated members

List with no separation --> This list has no separated members

Here is how the list is created, using Section:

List {
    ForEach(item, id: \.self) { item in
        Section {
            NavigationLink {
                VStack {
                    Text(name ?? "Err").font(.title)
                    Text(category ?? "Err").font(.subheadline)
                }
            } label: {
                HStack {
                    Text("\(order)")
                    Spacer()
                    Text(name ?? "Err")
                }
            }
        }
    }
}
.listStyle(.insetGrouped)
1 Answers

A possible solution for this is to turn off default row background and separators and make row drawing by ourselves using row insets to manage distances between rows... and this will not break default List bahavior.

Tested with Xcode 13.4 / iOS 15.5

demo

List {
    ForEach([1, 2, 3], id: \.self) { item in
        NavigationLink {
            VStack {
                Text("name \(item)").font(.title)
            }
        } label: {
            HStack {
                Text("\(item)")
                Spacer()
                Text("name \(item)").font(.title)
            }
        }
        .padding(.horizontal)
    }
    .background(RoundedRectangle(cornerRadius: 12).fill(.red))
    .listRowBackground(Color.clear)
    .listRowSeparator(.hidden)
    .listRowInsets(EdgeInsets(top: 4, leading: 0, bottom: 4, trailing: 0))
}
.listStyle(.insetGrouped)
Related