Apply pinch to zoom to any view in SwiftUI — iOS

Jakir Hossain
2 min readMar 27, 2024

I’ve previously discussed implementing the zoom feature for images. However, we can apply pinch-to-zoom functionality to any view in SwiftUI using the MagnificationGesture. Here is an example:

import SwiftUI

struct ContentView: View {
@State private var currentZoom = 0.0
@State private var totalZoom = 1.0
var body: some View {
Circle()
.fill(.blue)
.frame(width: 200, height: 200)
.scaleEffect(currentZoom + totalZoom)
.gesture(
MagnificationGesture()
.onChanged { value in
currentZoom = value - 1
}
.onEnded { value in
totalZoom += currentZoom
currentZoom = 0
}
)
}
}

#Preview(){
ContentView()
}

You can pinch in or pinch out in simulator by holding Option key + holding mouse & then move.

Output:

We can apply pinch-to-zoom in Text view too:

import SwiftUI

struct ContentView: View {
@State private var currentZoom = 0.0
@State private var totalZoom = 1.0
var body: some View {
Text("Hello, World!")
.font(.title)
.scaleEffect(currentZoom + totalZoom)
.gesture(
MagnificationGesture()
.onChanged { value in
currentZoom = value - 1
}
.onEnded { value in
totalZoom += currentZoom
currentZoom = 0
}
)
}
}

#Preview(){
ContentView()
}

Output:

Let’s connect in LinkedIn and explore new opportunities together!

--

--