1

This is code of my List:

import SwiftUI

struct PaymentScreen: View {

    init() {
        UITableView.appearance().separatorStyle = .none
        UITableViewCell.appearance().backgroundColor = .black // I can change color of this paddings here
    }

    var body: some View {
        return VStack (alignment: .center) {
            List (Terminal.terminals, id: \.self.distance) { terminal in
                PayTerminalAdapter(terminal: terminal).background(Color.white)
            }
        }
    }
}

Screenshot of my list:

enter image description here

I can't remove black leading and trailing paddings and paddings between list elements. When I use ForEach (I have very long array of terminals) - i don't have problem with paddings, but it works so slowly, therefore ForEach is a bad choice for me. How can i remove black paddings in List?

alexbayker
  • 882
  • 9
  • 19

2 Answers2

1

Maybe you are looking for the .listRowInsets modifier.

Solution:

List {
    ForEach(Terminal.terminals, id: \.self.distance) {
        PayTerminalAdapter(terminal: terminal).background(Color.white)
    }
    .listRowInsets(EdgeInsets(top: 1, leading: 2, bottom: 1, trailing: 2))
}

In the above, you may have noticed that the List(data:) is now simply List(content:), and the data is moved to a ForEach(data:id:).
I am not sure if there is a SwiftUI bug but .listRowInsets works only on single items. This single item can then have multiple items though and still be reusable, so no worries.
However, just as a test, even though the following looks like it should work, it does not:

Example (not working):

List(0...100, id: \.self) { _ in
    Text("Custom row inset not being applied")
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.gray)
        .listRowInsets(EdgeInsets(top: 1, leading: 2, bottom: 1, trailing: 2))
}

So put your datasource in a ForEach and apply .listRowInsets on it.

Example (working):

List {
    ForEach(0...100, id: \.self) { _ in
        Text("Custom row inset being applied")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.gray)
    }
    .listRowInsets(EdgeInsets(top: 1, leading: 2, bottom: 1, trailing: 2))
}
staticVoidMan
  • 19,275
  • 6
  • 69
  • 98
  • Good! It works! But anyway interesting, why .listRowInsets() don't work, when i use only List, without ForEach? – alexbayker Apr 21 '20 at 10:46
  • @alexbayker I am not sure, it may be a bug with the way `List(data:id:)` internally works. If I do figure it out, I will update this answer. If this answer has helped, then kindly accept it :) – staticVoidMan Apr 21 '20 at 11:00
0

You should change .listRowBackground() for that.

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278