You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
session-ios/Session/Utilities/UIView+Draggable.swift

51 lines
2.4 KiB
Swift

2 years ago
// Copyright © 2022 Rangeproof Pty Ltd. All rights reserved.
import UIKit
import SessionUIKit
2 years ago
extension UIView {
func makeViewDraggable() {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanForDragging))
2 years ago
addGestureRecognizer(panGestureRecognizer)
}
@objc private func handlePanForDragging(_ gesture: UIPanGestureRecognizer) {
guard let superview: UIView = self.superview else { return }
let location = gesture.location(in: superview)
2 years ago
if let draggedView = gesture.view {
draggedView.center = location
2 years ago
if gesture.state == .ended {
if draggedView.frame.midX >= (superview.layer.frame.width / 2) {
2 years ago
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
draggedView.center.x = (superview.layer.frame.width - (draggedView.width() / 2) - Values.smallSpacing)
2 years ago
}, completion: nil)
}
else
{
2 years ago
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
draggedView.center.x = ((draggedView.width() / 2) + Values.smallSpacing)
2 years ago
}, completion: nil)
}
let topMargin = ((UIApplication.shared.keyWindow?.safeAreaInsets.top ?? 0) + Values.veryLargeSpacing)
2 years ago
if draggedView.frame.minY <= topMargin {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
draggedView.center.y = (topMargin + (draggedView.height() / 2))
2 years ago
}, completion: nil)
}
let bottomMargin = (UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0)
if draggedView.frame.maxY >= superview.layer.frame.height {
2 years ago
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
draggedView.center.y = (superview.layer.frame.height - (draggedView.height() / 2) - bottomMargin)
2 years ago
}, completion: nil)
}
}
}
}
}