A simple Swift protocol utilising the powerful UIKitDynamics API, which makes ANY UIView draggable within a boundary view that acts as collision body, with a single method call. Works for any UIView.
A simple protocol (No need to subclass, no need to implement methods and properties yourself. Just drop the BJDraggable file into your project) utilizing the powerful UIKitDynamics
API, which makes ANY UIView
draggable within a boundary view that acts as collision body, with a single method call.
Use pod 'BJDraggable'
OR
Drag and Drop the BJDraggable.swift file (Located inside the Source folder in repo.) into your Xcode project.
addDraggability
method on your view and pass in a boundary view and that's it:override func viewDidLoad() {
super.viewDidLoad()
self.loginView.addDraggability(withinView: self.view)
self.omegaView.addDraggability(withinView: self.omegaContainerView)
self.omegaContainerView.addDraggability(withinView: self.view)
self.signupButton.addDraggability(withinView: self.view)
}
UIEdgeInsets
parameter:self.loginView.addDraggability(withinView: self.view, withMargin: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
removeDraggability
method:@IBAction func removeDraggabilityButtonTouched(_ sender: UIButton) {
self.loginView.removeDraggability()
self.omegaView.removeDraggability()
self.omegaContainerView.removeDraggability()
self.signupButton.removeDraggability()
}
Note: Call removeDraggability()
in the deinit
of your UIViewController
or UIView
if your think you're done with it. This does the cleanup of memory and other variables used.
If you want the view to move to its original position (respecting its autolayout constraints) after removing draggability like in the example GIF above, set the shouldResetViewPositionAfterRemovingDraggability
property to true
. Default value is false
.
To visually highlight the boundary lines within which the drag will happen, you can make isDraggableDebugModeEnabled
property to true
. The effective boundary (with margins applied) will be highlighted in red color. Specifying your own color will be added in the next or subsequent commits.
left
, right
, top
, bottom
to simulate boundary.This code is distributed under the terms and conditions of the MIT license.