In this tutorial, we'll walk through creating an interactive grid in SwiftUI that responds to touch-and-hold gestures. This project demonstrates how to create a visually appealing layout with custom colors and animations.
Step 1: Setting Up the View Structure
We start by creating our ContentView struct:
struct ContentView: View {
@State private var selectedItems: Set<Int> = []
var body: some View {
VStack(alignment: .leading, spacing: 8) {
// Grid content will go here
}
.frame(minWidth: UIScreen.main.bounds.width, maxHeight: UIScreen.main.bounds.height, alignment: .topLeading)
.background(Color(hex: 0xe4f6ff).ignoresSafeArea())
}
}
We use a @State property wrapper to keep track of selected items. The outer VStack is sized to fill the screen and has a custom background color.
Step 2: Creating the Grid
Inside the VStack, we create a nested structure of VStack and HStack to form a 3x2 grid:
VStack (spacing: 8) {
ForEach(0..<3) { row in
HStack(alignment: .top, spacing: 8) {
ForEach(0..<2) { column in
let index = row * 2 + column
// Grid item content will go here
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
}
}
Step 3: Designing Grid Items
Each grid item is a RoundedRectangle with custom styling:
RoundedRectangle(cornerRadius: 24, style: .continuous)
.fill(Color(hex: 0x7fd2ff))
.opacity(selectedItems.contains(index) ? 0.5 : 1.0)
.animation(.easeInOut(duration: 0.2), value: selectedItems.contains(index))
We use a custom Color initializer to create colors from hex values.
Step 4: Adding Touch Gestures
We add a DragGesture to each grid item to handle touch-and-hold interactions:
.gesture(
DragGesture(minimumDistance: 0)
.onChanged { _ in
if !selectedItems.contains(index) {
selectedItems.insert(index)
}
}
.onEnded { _ in
selectedItems.remove(index)
}
)
This gesture detects when a touch starts (onChanged) and ends (onEnded), updating the selectedItems set accordingly.