Skip to content

SwiftUI: Drag Gesture

Image allows you to showcase different variation of design in your app.

A dragging motion that invokes an action as the drag-event sequence changes.

Apple Documentation

In this tutorial, you’ll learn what is Drag Gesture in SwiftUI. You’ll learn:

  • How to use .onChanged.
  • How to use .updating.
  • How to use .onEnded.
  • How to limit scrolling.

Prerequisites

To follow along this tutorial, you’ll need some basic knowledge in:

  • A basic familiarity with Swift.
  • At least Xcode 11

.onChanged

onChanged changes the value of the location of the object that you drag. This will then move the object around.

First, let’s create a variable that can store the size. With the variable below, the object is now placed at the coordinate 50 in both x and y.

When the rectangle moves, you will change the rectPosition.

As a result, you have a moving rectangle.

.updating

You can know if the user is dragging or not by reading the state. First, create GestureState that will hold a value

Here, you can’t update the isDragging as it is read-only. But, you can update the state which will then update isDragging.

.onEnded

Perhaps you would only like certain action after the user is done dragging the object. First, create a variable to know if the user has end dragging or not.

Using the same code and maybe a little tweak, you would want the color to change if the x is less than 120.

And this is the result:

Limit horizontal scrolling

Too much dragging around the screen, my app doesn’t quite support that feature. What about just horizontal dragging?

If you would only like it to scroll vertically, then you may only consider changing the value to y.

Where to go From Here

If you feel like you are ready to take on more challenges, feel free to check out some other tutorials that we have created:

Published inSwiftUI

One Comment

  1. Ian Ian

    Thanks for the great Tutorial! It helped a lot.

    Is it possible to use if-statements in .onChanged?

    For Example if I want recognise when the user is dragging up or down?

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © DaddyCoding 2020.