SwiftUI - Remove space between cells

2020-06-03 05:39发布

问题:

I am implementing a list view in SwiftUI. What I am trying to approach is to have cells that has no space between any other cells or parent view.

So in this screenshot as you can see there is a space between every cell and also space with the edge of the phone, which I want to remove.

struct FlickrView : View {
    var flickrResponse: [FlickrResponse]
    var body: some View {
        List(flickrResponse) { item in
            FlickrImageCell(response: item)
        }
    }
}

struct FlickrImageCell : View {
    var response: FlickrResponse
    var body: some View {
        return ZStack(alignment: .topLeading) {
            Image(uiImage: response.image ?? UIImage())
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: nil, height: 100.0, alignment: .center)
                .clipShape(Rectangle())
                .padding(0)
            Text(response.title).fontWeight(.medium).multilineTextAlignment(.center)
        }
    }
}

I have tried this modifier:

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

But I have two problems with this approach: First, I don't think its convenient to write literal negative values. Second, the bottom padding does not work with any value.

So any suggestions?

回答1:

I've had good luck with listRowInsets

struct ContentView: View {
    var body: some View {
        List {
            Color.red
            .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
            Color.blue
            .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
            Color.yellow
            .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
        }
    }
}


标签: swift swiftui