I have LazyVGrid and inside I have a custom view that can changes it's height based on the image ratio the description etc ... the grid is sizing the view correctly but then the vertical spacing between each view varies based on the size of the view like in the image. I want the vertical spacing always remains at 8 point. like in this image the third cell must be attached to the first one with 8 points of spacing. I copied my code here I have given it already a spacing attribute. Also I tried to put height as infinity for the custom view but it didn't work. How Can I have a fixed vertical spacing between grid Items?
import SwiftUI
public struct NewsFeedView: View {
@StateObject private var viewModel = NewsViewModel()
let columns: [GridItem] = [
GridItem(.flexible(), spacing: 8),
GridItem(.flexible(), spacing: 8)
]
public var body: some View {
LazyVGrid(columns: columns, alignment: .leading, spacing: 8.0) {
ForEach(viewModel.newsItems) { newsItem in
NewsCell(newsItem: newsItem)
.frame(minHeight: 100, maxHeight: .infinity)
}
}
.padding(16)
}
}
public struct NewsCell: View {
@ObservedObject var newsItem: NewsItemViewModel
public var body: some View {
VStack(alignment: .leading, spacing: 8) {
Image(systemName: "heart") //.scaledToFit()
.resizable()
.aspectRatio(CGFloat(newsItem.imageAspectRatio), contentMode: .fit)
.background(Color.black)
Text(newsItem.title)
.lineLimit(nil)
.font(.headline)
Text(newsItem.subtitle)
.lineLimit(nil)
.font(.subheadline)
.foregroundColor(.gray)
Text(newsItem.description)
.lineLimit(nil)
.foregroundColor(.black)
if !newsItem.tags.isEmpty {
Divider()
VStack(alignment: .leading, spacing: 4) {
ForEach(newsItem.tags) { tag in
Text(tag.label)
.font(.footnote)
.foregroundColor(.blue)
}
}
}
}
.padding()
.background(Color.white)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.gray, lineWidth: 1)
)
}
}
With a grid, both the rows and the columns are always aligned. Based on your answer to my comment, it sounds like you don't want row alignment. That means, you don't want a grid.
Try using an HStack
as the container for two LazyVStack
instead:
HStack(spacing: 8) {
LazyVStack(spacing: 8) {
// ...
}
.frame(maxWidth: .infinity)
LazyVStack(spacing: 8) {
// ...
}
.frame(maxWidth: .infinity)
}
However, you will have to manage the distribution of items between the two stacks yourself.