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
Imageobjects (photos) as input. columnsdefines 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
ScrollViewto enable scrolling if the content exceeds the available space.
- Wraps the grid in a
- LazyVGrid:
LazyVGridis used to create a vertical grid layout. It’s more efficient than a regularVStackwhen you have many items, as it loads views lazily as they become visible.columns: columnsapplies the three-column layout defined earlier.spacing: 10adds 10 points of spacing between the grid items.
- ForEach:
- Iterates over the
photosarray, 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
PhotoGalleryViewand 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
LazyVGridfor an efficient and flexible grid layout. - Scrollable Content: Wraps the grid in a
ScrollViewto 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.