-
Notifications
You must be signed in to change notification settings - Fork 34
/
DragDropCollectionView.swift
355 lines (303 loc) · 15.5 KB
/
DragDropCollectionView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
//
// DragDropCollectionView.swift
// DragDrop
//
// Created by Lior Neu-ner on 2014/12/30.
// Copyright (c) 2014 LiorN. All rights reserved.
// 3rd test for git submodule
//Just testing git subtree for the second time
import UIKit
@objc protocol DrapDropCollectionViewDelegate {
func dragDropCollectionViewDidMoveCellFromInitialIndexPath(_ initialIndexPath: IndexPath, toNewIndexPath newIndexPath: IndexPath)
@objc optional func dragDropCollectionViewDraggingDidBeginWithCellAtIndexPath(_ indexPath: IndexPath)
@objc optional func dragDropCollectionViewDraggingDidEndForCellAtIndexPath(_ indexPath: IndexPath)
}
class DragDropCollectionView: UICollectionView, UIGestureRecognizerDelegate {
weak var draggingDelegate: DrapDropCollectionViewDelegate?
var longPressRecognizer: UILongPressGestureRecognizer = {
let longPressRecognizer = UILongPressGestureRecognizer()
longPressRecognizer.delaysTouchesBegan = false
longPressRecognizer.cancelsTouchesInView = false
longPressRecognizer.numberOfTouchesRequired = 1
longPressRecognizer.minimumPressDuration = 0.1
longPressRecognizer.allowableMovement = 10.0
return longPressRecognizer
}()
fileprivate var draggedCellIndexPath: IndexPath?
var draggingView: UIView?
fileprivate var touchOffsetFromCenterOfCell: CGPoint?
var isWiggling = false
fileprivate let pingInterval = 0.3
var isAutoScrolling = false
override var intrinsicContentSize: CGSize {
self.layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: self.contentSize.height)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
commonInit()
}
fileprivate func commonInit() {
longPressRecognizer.addTarget(self, action: #selector(DragDropCollectionView.handleLongPress(_:)))
longPressRecognizer.isEnabled = false
self.addGestureRecognizer(longPressRecognizer)
}
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
@objc func handleLongPress(_ longPressRecognizer: UILongPressGestureRecognizer) {
let touchLocation = longPressRecognizer.location(in: self)
switch (longPressRecognizer.state) {
case UIGestureRecognizerState.began:
draggedCellIndexPath = self.indexPathForItem(at: touchLocation)
if (draggedCellIndexPath != nil) {
draggingDelegate?.dragDropCollectionViewDraggingDidBeginWithCellAtIndexPath?(draggedCellIndexPath!)
let draggedCell = self.cellForItem(at: draggedCellIndexPath! as IndexPath) as UICollectionViewCell?
draggingView = UIImageView(image: getRasterizedImageCopyOfCell(draggedCell!))
draggingView!.center = (draggedCell!.center)
self.addSubview(draggingView!)
draggedCell!.alpha = 0.0
touchOffsetFromCenterOfCell = CGPoint(x: draggedCell!.center.x - touchLocation.x, y: draggedCell!.center.y - touchLocation.y)
UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.draggingView!.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.draggingView!.alpha = 0.8
})
}
case UIGestureRecognizerState.changed:
if draggedCellIndexPath != nil {
draggingView!.center = CGPoint(x: touchLocation.x + touchOffsetFromCenterOfCell!.x, y: touchLocation.y + touchOffsetFromCenterOfCell!.y)
if !isAutoScrolling {
dispatchOnMainQueueAfter(pingInterval, closure: { () -> () in
let scroller = self.shouldAutoScroll(touchLocation)
if (scroller.shouldScroll) {
self.autoScroll(scroller.direction)
self.isAutoScrolling = true
}
})
}
dispatchOnMainQueueAfter(pingInterval, closure: { () -> () in
let shouldSwapCellsTuple = self.shouldSwapCells(touchLocation)
if shouldSwapCellsTuple.shouldSwap {
self.swapDraggedCellWithCellAtIndexPath(shouldSwapCellsTuple.newIndexPath!)
}
})
}
case UIGestureRecognizerState.ended:
if draggedCellIndexPath != nil {
draggingDelegate?.dragDropCollectionViewDraggingDidEndForCellAtIndexPath?(draggedCellIndexPath!)
let draggedCell = self.cellForItem(at: draggedCellIndexPath! as IndexPath)
UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.draggingView!.transform = CGAffineTransform.identity
self.draggingView!.alpha = 1.0
if (draggedCell != nil) {
self.draggingView!.center = draggedCell!.center
}
}, completion: { (finished) -> Void in
self.draggingView!.removeFromSuperview()
self.draggingView = nil
draggedCell?.alpha = 1.0
self.draggedCellIndexPath = nil
})
}
default: ()
}
}
func enableDragging(_ enable: Bool) {
if enable {
longPressRecognizer.isEnabled = true
} else {
longPressRecognizer.isEnabled = false
}
}
fileprivate func shouldSwapCells(_ previousTouchLocation: CGPoint) -> (shouldSwap: Bool, newIndexPath: IndexPath?) {
var shouldSwap = false
var newIndexPath: IndexPath?
let currentTouchLocation = self.longPressRecognizer.location(in: self)
if !Double(currentTouchLocation.x).isNaN && !Double(currentTouchLocation.y).isNaN {
if distanceBetweenPoints(previousTouchLocation, secondPoint: currentTouchLocation) < CGFloat(20.0) {
if let newIndexPathForCell = self.indexPathForItem(at: currentTouchLocation) {
if newIndexPathForCell != self.draggedCellIndexPath! as IndexPath {
shouldSwap = true
newIndexPath = newIndexPathForCell
}
}
}
}
return (shouldSwap, newIndexPath)
}
fileprivate func swapDraggedCellWithCellAtIndexPath(_ newIndexPath: IndexPath) {
self.moveItem(at: self.draggedCellIndexPath! as IndexPath, to: newIndexPath as IndexPath)
let draggedCell = self.cellForItem(at: newIndexPath as IndexPath)!
draggedCell.alpha = 0
self.draggingDelegate?.dragDropCollectionViewDidMoveCellFromInitialIndexPath(self.draggedCellIndexPath!, toNewIndexPath: newIndexPath)
self.draggedCellIndexPath = newIndexPath
}
}
//AutoScroll
extension DragDropCollectionView {
enum AutoScrollDirection: Int {
case invalid = 0
case towardsOrigin = 1
case awayFromOrigin = 2
}
func autoScroll(_ direction: AutoScrollDirection) {
let currentLongPressTouchLocation = self.longPressRecognizer.location(in: self)
var increment: CGFloat
var newContentOffset: CGPoint
if (direction == AutoScrollDirection.towardsOrigin) {
increment = -50.0
} else {
increment = 50.0
}
newContentOffset = CGPoint(x: self.contentOffset.x, y: self.contentOffset.y + increment)
let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
if flowLayout.scrollDirection == UICollectionView.ScrollDirection.horizontal{
newContentOffset = CGPoint(x: self.contentOffset.x + increment, y: self.contentOffset.y)
}
if ((direction == AutoScrollDirection.towardsOrigin && newContentOffset.y < 0) || (direction == AutoScrollDirection.awayFromOrigin && newContentOffset.y > self.contentSize.height - self.frame.height)) {
dispatchOnMainQueueAfter(0.3, closure: { () -> () in
self.isAutoScrolling = false
})
} else {
UIView.animate(withDuration: 0.3
, delay: 0.0
, options: UIView.AnimationOptions.curveLinear
, animations: { () -> Void in
self.setContentOffset(newContentOffset, animated: false)
if (self.draggingView != nil) {
if flowLayout.scrollDirection == UICollectionView.ScrollDirection.vertical{
var draggingFrame = self.draggingView!.frame
draggingFrame.origin.y += increment
self.draggingView!.frame = draggingFrame
}else{
var draggingFrame = self.draggingView!.frame
draggingFrame.origin.x += increment
self.draggingView!.frame = draggingFrame
}
}
}) { (finished) -> Void in
dispatchOnMainQueueAfter(0.0, closure: { () -> () in
var updatedTouchLocationWithNewOffset = CGPoint(x: currentLongPressTouchLocation.x, y: currentLongPressTouchLocation.y + increment)
if flowLayout.scrollDirection == UICollectionView.ScrollDirection.horizontal{
updatedTouchLocationWithNewOffset = CGPoint(x: currentLongPressTouchLocation.x + increment, y: currentLongPressTouchLocation.y)
}
let scroller = self.shouldAutoScroll(updatedTouchLocationWithNewOffset)
if scroller.shouldScroll {
self.autoScroll(scroller.direction)
} else {
self.isAutoScrolling = false
}
})
}
}
}
func shouldAutoScroll(_ previousTouchLocation: CGPoint) -> (shouldScroll: Bool, direction: AutoScrollDirection) {
let previousTouchLocation = self.convert(previousTouchLocation, to: self.superview)
let currentTouchLocation = self.longPressRecognizer.location(in: self.superview)
if let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout {
if !Double(currentTouchLocation.x).isNaN && !Double(currentTouchLocation.y).isNaN {
if distanceBetweenPoints(previousTouchLocation, secondPoint: currentTouchLocation) < CGFloat(20.0) {
let scrollDirection = flowLayout.scrollDirection
var scrollBoundsSize: CGSize
let scrollBoundsLength: CGFloat = 50.0
var scrollRectAtEnd: CGRect
switch scrollDirection {
case UICollectionViewScrollDirection.horizontal:
scrollBoundsSize = CGSize(width: scrollBoundsLength, height: self.frame.height)
scrollRectAtEnd = CGRect(x: self.frame.origin.x + self.frame.width - scrollBoundsSize.width , y: self.frame.origin.y, width: scrollBoundsSize.width, height: self.frame.height)
case UICollectionViewScrollDirection.vertical:
scrollBoundsSize = CGSize(width: self.frame.width, height: scrollBoundsLength)
scrollRectAtEnd = CGRect(x: self.frame.origin.x, y: self.frame.origin.y + self.frame.height - scrollBoundsSize.height, width: self.frame.width, height: scrollBoundsSize.height)
}
let scrollRectAtOrigin = CGRect(origin: self.frame.origin, size: scrollBoundsSize)
if scrollRectAtOrigin.contains(currentTouchLocation) {
return (true, AutoScrollDirection.towardsOrigin)
} else if scrollRectAtEnd.contains(currentTouchLocation) {
return (true, AutoScrollDirection.awayFromOrigin)
}
}
}
}
return (false, AutoScrollDirection.invalid)
}
}
//Wiggle Animation
extension DragDropCollectionView {
func startWiggle() {
for cell in visibleCells {
addWiggleAnimationTo(cell )
}
isWiggling = true
}
func stopWiggle() {
for cell in visibleCells {
cell.layer.removeAllAnimations()
}
isWiggling = false
}
override func dequeueReusableCell(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> UICollectionViewCell {
let cell: AnyObject = super.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath as IndexPath)
if isWiggling {
addWiggleAnimationTo(cell as! UICollectionViewCell)
} else {
cell.layer.removeAllAnimations()
}
return cell as! UICollectionViewCell
}
func addWiggleAnimationTo(_ cell: UICollectionViewCell) {
CATransaction.begin()
CATransaction.setDisableActions(false)
cell.layer.add(rotationAnimation(), forKey: "rotation")
cell.layer.add(bounceAnimation(), forKey: "bounce")
CATransaction.commit()
}
fileprivate func rotationAnimation() -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
let angle = CGFloat(0.04)
let duration = TimeInterval(0.1)
let variance = Double(0.025)
animation.values = [angle, -angle]
animation.autoreverses = true
animation.duration = self.randomize(duration, withVariance: variance)
animation.repeatCount = Float.infinity
return animation
}
fileprivate func bounceAnimation() -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.y")
let bounce = CGFloat(3.0)
let duration = TimeInterval(0.12)
let variance = Double(0.025)
animation.values = [bounce, -bounce]
animation.autoreverses = true
animation.duration = self.randomize(duration, withVariance: variance)
animation.repeatCount = Float.infinity
return animation
}
fileprivate func randomize(_ interval: TimeInterval, withVariance variance:Double) -> TimeInterval {
let random = (Double(arc4random_uniform(1000)) - 500.0) / 500.0
return interval + variance * random;
}
}
//Assisting Functions
extension DragDropCollectionView {
func getRasterizedImageCopyOfCell(_ cell: UICollectionViewCell) -> UIImage {
UIGraphicsBeginImageContextWithOptions(cell.bounds.size, false, 0.0)
cell.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
public func dispatchOnMainQueueAfter(_ delay:Double, closure:@escaping ()->Void) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+delay, qos: DispatchQoS.userInteractive, flags: DispatchWorkItemFlags.enforceQoS, execute: closure)
}
public func distanceBetweenPoints(_ firstPoint: CGPoint, secondPoint: CGPoint) -> CGFloat {
let xDistance = firstPoint.x - secondPoint.x
let yDistance = firstPoint.y - secondPoint.y
return sqrt(xDistance * xDistance + yDistance * yDistance)
}