Simple Image Grid
We are going to use a 2D array to create the grid. Inside a
VStack, add a
ForEach loop that takes the 2D array. For each array of images inside our 2D array, add a second loop (from 0 to less than 3). Check if the index is not out of range, then add the
Image view. When the index is out of range, add an empty
Rectangle(). If you don’t want to use a
Rectangle(), then you can use leading alignment and re-center the grid.
Image view, add the
aspectRatio() modifier and set its content mode to
fill. Use the resizable modifier to be able to change the image’s frame, then add the frame modifier to adjust the size of the images.
To make square images, make sure to have the same value for the width and height. Lastly, clip the image by using the
Create a custom image view that has a
binding image string variable. Make sure to use shadow to make the image pop out.
Back to our
ContentView. Declare two new variables:
isDetectingLongPress: Gesture state variable. For detecting long-press gestures and controlling the image preview.
img: State variable used to pass the image to preview to the
ImagePreviewwe created above.
Embed the grid code above inside a
ZStack. Under the grid, add the
ImagePreview we created above inside an
if statement that checks whether a long press occurred or not:
Image view inside the grid, add a gesture modifier and pass it a
LongPressGesture() with a minimum duration of 60. The duration determines how long the
ImagePreview will last if the user didn’t end the long-press gesture. Inside the
updating() modifier, add a spring animation to the transaction. In the
onChanged() modifier, assign the image string that will be passed to the
ImagePreview to the image that has been pressed:
Lastly, add the
.blur() modifier to the
VStack. Alter its radius value between 0 and 5 when a long press is detected:
All done! Thanks for reading.