Creating a Draggable iOS View
Some iOS apps have items like cards or sticky notes that you can drag. Making an iOS view draggable is less difficult than you think. Use a pan gesture recognizer, and you can drag a view around with your finger.
The Steps
Take the following steps to create a draggable view in iOS:
- Add a view to the view controller scene in your storyboard.
- Drag a pan gesture recognizer to the view so the view becomes draggable.
- Create an action (IBAction) for the pan gesture recognizer by making a connection from the storyboard to the view controller’s source code file. Set the type for the sender to
UIPanGestureRecognizer
.
I have a demo project for draggable views on GitHub.
The Code
To make the view move around when you drag it, you must implement the action for the pan gesture recognizer. The following code shows an example of panning a view:
@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)
}
}
By setting the type of the IBAction to UIPanGestureRecognizer
, you can access the view being dragged through the pan gesture recognizer’s view
property.
The first line of code determines how far the view dragged. Using an if-let
statement avoids force unwrapping optionals when accessing the dragged view.
The first line of code inside the if-let
block moves the center of the view by the amount of the drag. The second line of code clears the translation for future drags.