Skip to main content

How to handle pinch to zoom for views

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to handle pinch to zoom for views 관련

SwiftUI by Example

Back to Home

How to handle pinch to zoom for views | SwiftUI by Example

How to handle pinch to zoom for views

Updated for Xcode 15

SwiftUI provides MagnifyGesture for tracking pinch to zoom for views, which can be bound to a scaleEffect() modifier so the user’s pinch gesture automatically scales up or shrinks a view.

If you want to keep their zoom level once they finish the gesture, you should track their current and total zoom level together, like this:

struct ContentView: View {
    @State private var currentZoom = 0.0
    @State private var totalZoom = 1.0

    var body: some View {
        Image("singapore")
            .scaleEffect(currentZoom + totalZoom)
            .gesture(
                MagnifyGesture()
                    .onChanged { value in
                        currentZoom = value.magnification - 1
                    }
                    .onEnded { value in
                        totalZoom += currentZoom
                        currentZoom = 0
                    }
            )
            .accessibilityZoomAction { action in
                if action.direction == .zoomIn {
                    totalZoom += 1
                } else {
                    totalZoom -= 1
                }
            }
    }
}

Download this as an Xcode projectopen in new window

Tips

Subtract 1 from value.magnification is important, because 1 is its default value for a new gesture. Using the accessibilityZoomAction() modifier allows assistive technologies to control the zoom level.

On the other hand, if you want to track their gesture but reset back to 0 each time, use @GestureState like this:

struct ContentView: View {
    @GestureState private var zoom = 1.0

    var body: some View {
        Image("singapore")
            .scaleEffect(zoom)
            .gesture(
                MagnifyGesture()
                    .updating($zoom) { value, gestureState, transaction in
                        gestureState = value.magnification
                    }
            )
    }
}

Download this as an Xcode projectopen in new window

Similar solutions…
How to override animations with transactions | SwiftUI by Example

How to override animations with transactions
Composing views to create a list row | SwiftUI by Example

Composing views to create a list row
How to use @EnvironmentObject to share data between views | SwiftUI by Example

How to use @EnvironmentObject to share data between views
How to make two views the same width or height | SwiftUI by Example

How to make two views the same width or height
How to make views scroll with a custom transition | SwiftUI by Example

How to make views scroll with a custom transition

이찬희 (MarkiiimarK)
Never Stop Learning.