SwiftUI Magnification Gesture: The Simplest way to implement this nice gesture feature
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
I prepared a simple image.
[1] declare @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
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
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
That’s all! You’ve just completed adding this nice new feature!
Entire Code
Conclusion
- Declare a variable with @GestureState Property Wrapper
- Provide state declared with @GestureProperty to
updating()
view modifier - Create another variable if you want to keep the current scale
- Attach MagnificationGesture to View!