SwiftUI Magnification Gesture: The Simplest way to implement this nice gesture feature

KD Knowledge Diet
2 min readJun 12, 2022

SwiftUI already has a number of gestures that you can use to interact actively with the user. Developers just take it and use it. It’s much more intuitive than the old UIKit, so even difficult functions can be created faster than before. Apps without Gesture are incredibly boring. Successful apps already on the market actively use apple-provided APIs to interact with users! And why not you and me?

Prepare UI

Simple Image
Cat

I prepared a simple image.

[1] declare @GestureState

@GestureState

@GestureState is a property wrapper built to be conveniently used. It’s a State. You need to provide this state to Magnification gesture that you are going build.

[2] Declare Gesture

Magnification Gesture

Don’t panic. I will explain it one by one. First of all, when you instantiate MagnificationGesture(), you need to attach .updating($zoomFactor) modifier. This view modifier takes Binding. That’s why I just defined
@GestureState private var zoomFactor: CGFloat = 1.0. It is this value that you will use to update your views with Magnification Gesture.

.updating()

.updating modifier takes $zoomFactor and its trailing closure has three arguments.

  • value: value returned from Magnification Gesture
  • scale: current scale (marked as inout , it means you can change its value)
  • transaction: when you need to animate

.onChanged()

Following .updating, I attached onChanged. This modifier has closure that returns values that you assigned to scale. This is where you actually start magnifying.

.onEnded()

This is called lastly. When you attach this modifier, you will get notified when magnification gesture ends and it returns the value of its magnification.

[3] Create variable which keeps tracking of scales

current scale

Why do you need another variable? It’s because the variable zoomFactor here, doesn’t store the value. It always goes back to its initial value after gesture is complete. So if you want your view to keep its scale, you need another variable.

And take a look at onChanged. currentScale stores changed magnification value.

[4] Attach Magnification Gesture

magnification applied

That’s all! You’ve just completed adding this nice new feature!

Entire Code

Magnifying Gesture

Conclusion

  1. Declare a variable with @GestureState Property Wrapper
  2. Provide state declared with @GestureProperty to updating() view modifier
  3. Create another variable if you want to keep the current scale
  4. Attach MagnificationGesture to View!

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!