Search
Monday 23 September 2019
  • :
  • :

How To Create A Custom Dragging Views In Swift?

This tutorial is shared by iOS developers India to explain how to create a custom view with draggable functionality. You can follow the instructions shared by these experts in this post and create your custom dragging views in Swift.

One-liner: In this tutorial, we will create a random custom view with draggable functionality. This tutorial is implemented in Xcode 8 and built for iOS 10.

Start with creating one single view application with the product name “DraggingViews”. In the language field select swift language and devices field select universal.

First, we have to add one UIView class file for display random views for that go to

File –> New –> File –> iOS –> Cocoa Touch Class, name the class file DragView and subclass select UIView.Please check below screenshot for more info.

1

2

Open DragView.swift file and declare one variable with name lastLocation for tracking user the last touch. In init() method first declare variable panRecognizer of UIPanGestureRecognizer with call of findPan() method. After that randomly generate colors of red, green and blue for setting custom view background. All things show in below screenshot.

3

Next method is findPan() which is called when a user drags views from one position to another position. In this method, we get new coordinates of view when it panning. Center of view will adjust view according to changed coordinates. Please check below screenshot for more info.

4

Next, touchBegan:event() method called when the user clicks on a view. When user click on view that view show in front of other views.

5

Now open ViewController.swift and implement viewDidLoad() method. In this method, we add 30 custom views in the main view using for loop. The custom views place randomly in the main view with a random color. Please check below screenshot.

6

Now build and run the project. If everything is, correct your app should run properly, and you will see below output. You can check by dragging any view from one position to another position.

7

8

From step one to last; you have to follow every point shared by iOS developers India in this post for best results. You can review this article at the end of the comment section. Feedback for this post is always open.



Vijay is a compulsive blogger who likes to educate like-minded people on various new technologies and trends. He works with Aegis SoftTech as a software developer and has been developing software for years. Stay Connected to him on Facebook and Google+.