Drag and Drop Tasks using SwiftUI

Harshit Parakh
3 min readApr 26, 2021

Hello Everyone !!

As assured in my previous articles, SwiftUI or UIKit for new projects ? and Using property wrappers in SwiftUI, I would try my best to make you fall in ❤️ with SwiftUI.

Today we will create a Task Management application to see drag and drop using SwiftUI. We will be following MVVM architecture.
(You can find articles that demonstrate drag and drop in single list. We will see drag and drop in multiple lists.)

Getting Started

Download the source code from this Github repository to follow along and understand the usage better.

Here we have three states of task: Upcoming, In Progress and Completed.

Data Model

Each task has:

  • Title
  • Description
  • Status (Upcoming, In Progress, Completed). i.e. current state of the task.

Building a segmented control

If you’re following along check out the HomeView.swift file.
We can create a segment control in SwiftUI using a picker view and adding pickerStyle as SegmentedPickerStyle.

Building the Horizontal List View

Check out the HomeView.swift file.
Because we have three different states for our task so we need three different lists to show tasks respectively.

Adding the TaskListView

Check out the TaskListView.swift file.
In this list we show the tasks corresponding to the selected state. If no tasks are available then we show Empty state.

Key Notes:-

  • .onDrop : SwiftUI provides onDrop that allows us to register a closure that where we can handle it’s delegate methods. onDrop is generally added on the view where we want to perform the drop operation. In our case we have added onDrop on ScrollView.
  • For drops to work we need to add DropDelegate. In the drop delegate we can add our logic after drop is completed. We have used the performDrop(info: DropInfo) -> Bool method.

Building the task card view

Check out the TaskView.swift file.
Here our card view has two views i.e. Front View and Back View.
Front View displays the short information of the task and Back View displays the description of the task.

Task View

Front View

Back View

Key Notes:-

  • .onDrag : SwiftUI provides onDrag modifier that allows us to register a closure that will create and return NSItemProvider. We need to add onDrag to our card view.
  • .onTapGesture : SwiftUI provides onTapGesture that allows us to register a closure that will detect tap. We have added tap gesture to flip the card.
    We have also added custom modifier FlipEffect helper view on our card view.

Final Project

Summary

I hope this articles helps you in understanding drag and drop in SwiftUI.

More articles with projects are coming soon to make you fall in ❤️ with SwiftUI.

Please feel free to share your views and any suggestions / feedbacks are welcomed.

Thanks for reading.

--

--