How do I create a drag-able floating view on iOS?

Rlogical Techsoft
1 min readJan 4, 2021
source: medium.com

Let ‘s see here the following steps for making a drag-able floating view

1. Add a UIView to the view controller in storyboard.

2. Put on pan gesture to the UIView which is just added to the view controller therefore the view become draggable.

3. Create an IBAction for the pan gesture by making a connection to the storyboard to the view controller’s source code file.

4. Set the type for the sender to UIPanGestureRecognizer.

- Example like below :-

@IBAction func panView(_ sender: UIPanGestureRecognizer)
{
let translation = sender.translation(in: self.view)

if let viewToDrag = sender.view
{
viewToDrag.center = CGPoint(x: viewToDrag.center.x + translation.x,
y: viewToDrag.center.y + translation.y)
sender.setTranslation(CGPoint(x: 0, y: 0), in: viewToDrag)
}
}

- Explanation of code :-

By setting the type of the IBAction to UIPanGestureRecognizer, you can access the view being dragged through the pan gesture recogniser’s view property.

The first line of code determine how far the view dragged. Use optional Channing for avoid force unwrapping optionals or unnecessary crash (Use an If — let).

--

--

Rlogical Techsoft

Web & Mobile App Development Company. Expertise in Mobile App, PHP, ASP .NET, MVC 5 (Razor), MongoDB, NodeJS, AngularJS, ReactJS, Windows App, POS, Scraping.