Search code examples
swiftuigridmobile-development

Data to Image conversion looks weird inside a Grid


I have a basic SwiftData model with Images stored as Data.
In my view I have those 2 variables:

@State private var selectedImages = [PhotosPickerItem]()
@State private var images = [Data]()

And in my view it looks like this:

let columns = [
    GridItem(.adaptive(minimum: 80))
]

ScrollView {
    LazyVGrid(columns: columns) {
        ForEach(images, id: \.self) { image in
            let uiImage = UIImage(data: image)
            Image(uiImage: uiImage!)
                .resizable()
                .aspectRatio(contentMode: .fill)
        }
    }
}
.padding(.horizontal)

But if you look at the picture below, the sizing only works for the second row. The first one looks super weird.

Can someone explain why?

Image Bug


Solution

  • Okay I got.

    I changed the columns to this:

    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),        
        GridItem(.flexible())
    ]
    

    And removed the .aspectRatio and gave the images a fixed height

    ScrollView {
        LazyVGrid(columns: columns) {
            ForEach(images, id: \.self) { image in
                let uiImage = UIImage(data: image)
                Image(uiImage: uiImage!)
                    .resizable()
                    .frame(height: 85)
            }
        }
    }
    .padding(.horizontal)
    

    Now it looks better: Fixed Image Grid