
Here’s a SwiftUI implementation of a photo gallery using nested HStack
and VStack
to create a grid layout, along with explanations:
import SwiftUI
struct PhotoGalleryView: View {
let photos: [Image] // Array of Image objects for your photos
let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 3) // 3 columns
var body: some View {
ScrollView { // Make the gallery scrollable
LazyVGrid(columns: columns, spacing: 10) { // Lazy grid for performance
ForEach(photos.indices, id: \.self) { index in
photos[index]
.resizable()
.scaledToFill()
.frame(height: 150) // Adjust height as needed
.clipped()
}
}
.padding()
}
}
}
// Example Usage
struct ContentView: View {
var body: some View {
PhotoGalleryView(photos: [
Image("photo1"), // Replace with your image names
Image("photo2"),
Image("photo3"),
// ... more photos
])
}
}
struct PhotoGalleryView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Explanation:
- PhotoGalleryView:
- It takes an array of
Image
objects (photos
) as input. columns
defines a three-column grid layout using.flexible()
GridItems, meaning each column will take up equal space.
- It takes an array of
- ScrollView:
- Wraps the grid in a
ScrollView
to enable scrolling if the content exceeds the available space.
- Wraps the grid in a
- LazyVGrid:
LazyVGrid
is used to create a vertical grid layout. It’s more efficient than a regularVStack
when you have many items, as it loads views lazily as they become visible.columns: columns
applies the three-column layout defined earlier.spacing: 10
adds 10 points of spacing between the grid items.
- ForEach:
- Iterates over the
photos
array, using the indices for identification. - For each photo:
photos[index]
displays the corresponding image.resizable()
andscaledToFill()
make the image fit the grid item while maintaining its aspect ratio.frame(height: 150)
sets the height of each photo (adjust as needed).clipped()
clips any content that overflows the frame.
- Iterates over the
- Padding:
- Adds padding around the entire grid.
- Example Usage (ContentView):
- Creates a
PhotoGalleryView
and passes an array of sample image names (photo1
,photo2
, etc.). Make sure to replace these with the actual names of your images in your project’s asset catalog.
- Creates a
Key Improvements:
- Grid Layout: Uses
LazyVGrid
for an efficient and flexible grid layout. - Scrollable Content: Wraps the grid in a
ScrollView
to handle large photo galleries. - Image Handling: Images are resized and clipped to fit within the grid items.
- Customization: You can easily adjust the number of columns, spacing, image height, and add more styling or functionality to the photos.