session-ios/Session/Utilities/UIView+Draggable.swift

51 lines
2.4 KiB
Swift
Raw Permalink Normal View History

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