Search
Saturday 24 June 2017
  • :
  • :

How To Create A Custom Dragging Views In Swift?

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

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

Start with creating one single view application with product name “DraggingViews”. In 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 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 are show in below screen shot.

3

Next method is findPan() which is called when user drag view 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 main view using for loop. The custom views place randomly in main view with random color. Please check below screen shot.

6

Now build and run 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 in 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+.