How to remove insets and row separator from Table?

120 views Asked by At

I am looking for a way to remove insets (and ideally row separators) in SwiftUI's Table.

Lists have:

.listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))

and

.listRowSeparator(.hidden)

respectively.

Neither Table's @TableRowBuilder, @TableColumnBuilder or the Table itself appear to have any modifiers for inset manipulation?

2

There are 2 answers

1
Andrew James On

You need to put the modifiers on the List item - below example with commented out lines to compare. You could extract the List items into a passed in View to make this simpler

List{
  Text("Row 1 \(Date.now.formatted(date: .numeric, time: .complete))")
    .listRowSeparatorTint(.red)
    .listRowSeparator(.hidden)
    .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
  Text("Row 2 \(Date.now.formatted(date: .numeric, time: .complete))")
    .listRowSeparatorTint(.red)
    .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
//  .listRowSeparator(.hidden)
  Text("Row 3 \(Date.now.formatted(date: .numeric, time: .complete))")
    .listRowSeparatorTint(.red)
//  .listRowSeparator(.hidden)
  Text("Row 4 \(Date.now.formatted(date: .numeric, time: .complete))"
}
2
Navneet Kaur On
struct CustomTableRow<Content: View>: View {
let content: Content

init(@ViewBuilder content: () -> Content) {
    self.content = content()
}

var body: some View {
    content
        .padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
        .frame(maxWidth: .infinity, alignment: .leading) // Adjust alignment as needed
}
}

// Usage:
struct ContentView: View {
var body: some View {
    Table {
        TableRow {
            CustomTableRow {
                Text("Row 1")
            }
        }
        TableRow {
            CustomTableRow {
                Text("Row 2")
            }
        }
        // Add more TableRow as needed
    }
    .border(Color.gray, width: 1) // Add border for demonstration
}
}

In this:

We define a CustomTableRow view that accepts content with the help of a @ViewBuilder.

Within CustomTableRow, we apply padding to customise the inserts as needed.

You can also customise the alignment of the content within the row using .frame.