-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathLxGridViewFlowLayout.swift
412 lines (280 loc) · 15.7 KB
/
LxGridViewFlowLayout.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//
// LxGridViewFlowLayout.swift
// LxGridViewDemo
//
import UIKit
let PRESS_TO_MOVE_MIN_DURATION = 0.1
let MIN_PRESS_TO_BEGIN_EDITING_DURATION = 0.6
@objc
protocol LxGridViewDataSource : UICollectionViewDataSource {
optional func collectionView(collectionView: LxGridView, itemAtIndexPath sourceIndexPath: NSIndexPath, willMoveToIndexPath destinationIndexPath: NSIndexPath)
optional func collectionView(collectionView: LxGridView, itemAtIndexPath sourceIndexPath: NSIndexPath, didMoveToIndexPath destinationIndexPath: NSIndexPath)
optional func collectionView(collectionView: LxGridView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool
optional func collectionView(collectionView: LxGridView, itemAtIndexPath sourceIndexPath: NSIndexPath, canMoveToIndexPath destinationIndexPath: NSIndexPath) -> Bool
}
@objc
protocol LxGridViewDelegateFlowLayout : UICollectionViewDelegateFlowLayout {
optional func collectionView(collectionView: LxGridView, layout gridViewLayout: LxGridViewFlowLayout, willBeginDraggingItemAtIndexPath indexPath: NSIndexPath)
optional func collectionView(collectionView: LxGridView, layout gridViewLayout: LxGridViewFlowLayout, didBeginDraggingItemAtIndexPath indexPath: NSIndexPath)
optional func collectionView(collectionView: LxGridView, layout gridViewLayout: LxGridViewFlowLayout, willEndDraggingItemAtIndexPath indexPath: NSIndexPath)
optional func collectionView(collectionView: LxGridView, layout gridViewLayout: LxGridViewFlowLayout, didEndDraggingItemAtIndexPath indexPath: NSIndexPath)
}
class LxGridViewFlowLayout: UICollectionViewFlowLayout, UIGestureRecognizerDelegate {
var panGestureRecognizerEnable: Bool {
get {
return _panGestureRecognizer.enabled
}
set {
_panGestureRecognizer.enabled = newValue
}
}
var _panGestureRecognizer = UIPanGestureRecognizer()
var _longPressGestureRecognizer = UILongPressGestureRecognizer()
var _movingItemIndexPath: NSIndexPath?
var _beingMovedPromptView: UIView?
var _sourceItemCollectionViewCellCenter = CGPointZero
var _displayLink: CADisplayLink?
var _remainSecondsToBeginEditing = MIN_PRESS_TO_BEGIN_EDITING_DURATION
// MARK:- setup
deinit {
_displayLink?.invalidate()
removeGestureRecognizers()
removeObserver(self, forKeyPath: "collectionView")
}
override init () {
super.init()
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
self.addObserver(self, forKeyPath: "collectionView", options: .New, context: nil)
}
func addGestureRecognizers() {
collectionView?.userInteractionEnabled = true
_longPressGestureRecognizer.addTarget(self, action: Selector("longPressGestureRecognizerTriggerd:"))
_longPressGestureRecognizer.cancelsTouchesInView = false
_longPressGestureRecognizer.minimumPressDuration = PRESS_TO_MOVE_MIN_DURATION
_longPressGestureRecognizer.delegate = self
if let cV = collectionView {
for gestureRecognizer in cV.gestureRecognizers! {
if gestureRecognizer is UILongPressGestureRecognizer {
gestureRecognizer.requireGestureRecognizerToFail(_longPressGestureRecognizer)
}
}
}
collectionView?.addGestureRecognizer(_longPressGestureRecognizer)
_panGestureRecognizer.addTarget(self, action: Selector("panGestureRecognizerTriggerd:"))
_panGestureRecognizer.delegate = self
collectionView?.addGestureRecognizer(_panGestureRecognizer)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("applicationWillResignActive:"), name: UIApplicationWillResignActiveNotification, object: nil)
}
func removeGestureRecognizers() {
_longPressGestureRecognizer.view?.removeGestureRecognizer(_longPressGestureRecognizer)
_longPressGestureRecognizer.delegate = nil
_panGestureRecognizer.view?.removeGestureRecognizer(_panGestureRecognizer)
_panGestureRecognizer.delegate = nil
NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: UIApplicationWillResignActiveNotification)
}
// MARK:- getter and setter implementation
var dataSource: LxGridViewDataSource? {
return collectionView?.dataSource as? LxGridViewDataSource
}
var delegate: LxGridViewDelegateFlowLayout? {
return collectionView?.delegate as? LxGridViewDelegateFlowLayout
}
var editing: Bool {
set {
assert(collectionView is LxGridView || collectionView == nil, "LxGridViewFlowLayout: Must use LxGridView as your collectionView class!")
if let gridView = collectionView as? LxGridView {
gridView.editing = newValue
}
}
get {
assert(collectionView is LxGridView || collectionView == nil, "LxGridViewFlowLayout: Must use LxGridView as your collectionView class!")
if let gridView = collectionView as? LxGridView {
return gridView.editing
}
else {
return false
}
}
}
// MARK:- override UICollectionViewLayout methods
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
let layoutAttributesForElementsInRect = super.layoutAttributesForElementsInRect(rect)
if let lxfeir = layoutAttributesForElementsInRect {
for layoutAttributes in lxfeir {
if let las = layoutAttributes as? UICollectionViewLayoutAttributes {
if las.representedElementCategory == .Cell {
las.hidden = las.indexPath == _movingItemIndexPath
}
}
}
}
return layoutAttributesForElementsInRect
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let layoutAttributes = super.layoutAttributesForItemAtIndexPath(indexPath)
if layoutAttributes.representedElementCategory == .Cell {
layoutAttributes.hidden = layoutAttributes.indexPath == _movingItemIndexPath
}
return layoutAttributes
}
// MARK:- gesture
func longPressGestureRecognizerTriggerd(longPress:UILongPressGestureRecognizer) {
switch longPress.state {
case .Began:
if _displayLink == nil {
_displayLink = CADisplayLink(target: self, selector: Selector("displayLinkTriggered:"))
_displayLink?.frameInterval = 6
_displayLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
_remainSecondsToBeginEditing = MIN_PRESS_TO_BEGIN_EDITING_DURATION
}
if editing == false {
return
}
_movingItemIndexPath = collectionView?.indexPathForItemAtPoint(longPress.locationInView(collectionView))
if dataSource?.collectionView?(collectionView as! LxGridView, canMoveItemAtIndexPath: _movingItemIndexPath!) == false {
_movingItemIndexPath = nil
return
}
delegate?.collectionView?(collectionView as! LxGridView, layout: self, willBeginDraggingItemAtIndexPath: _movingItemIndexPath!)
if _movingItemIndexPath == nil {
return
}
let sourceCollectionViewCell = collectionView?.cellForItemAtIndexPath(_movingItemIndexPath!)
assert(sourceCollectionViewCell is LxGridViewCell || sourceCollectionViewCell == nil, "LxGridViewFlowLayout: Must use LxGridViewCell as your collectionViewCell class!")
let sourceGridViewCell = sourceCollectionViewCell as! LxGridViewCell
_beingMovedPromptView = UIView(frame: CGRectOffset(sourceCollectionViewCell!.frame, -LxGridView_DELETE_RADIUS, -LxGridView_DELETE_RADIUS))
sourceGridViewCell.highlighted = true
let highlightedSnapshotView = sourceGridViewCell.snapshotView()
highlightedSnapshotView.frame = sourceGridViewCell.bounds
highlightedSnapshotView.alpha = 1
sourceGridViewCell.highlighted = false
let snapshotView = sourceGridViewCell.snapshotView()
snapshotView.frame = sourceGridViewCell.bounds
snapshotView.alpha = 0
_beingMovedPromptView?.addSubview(snapshotView)
_beingMovedPromptView?.addSubview(highlightedSnapshotView)
collectionView?.addSubview(_beingMovedPromptView!)
let kVibrateAnimation = "kVibrateAnimation"
let VIBRATE_DURATION: CGFloat = 0.1
let VIBRATE_RADIAN = CGFloat(M_PI/96)
let vibrateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
vibrateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
vibrateAnimation.fromValue = -VIBRATE_RADIAN
vibrateAnimation.toValue = VIBRATE_RADIAN
vibrateAnimation.autoreverses = true
vibrateAnimation.duration = CFTimeInterval(VIBRATE_DURATION)
vibrateAnimation.repeatCount = Float(CGFloat.max)
_beingMovedPromptView?.layer.addAnimation(vibrateAnimation, forKey: kVibrateAnimation)
_sourceItemCollectionViewCellCenter = sourceGridViewCell.center
UIView.animateWithDuration(0, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in
highlightedSnapshotView.alpha = 0
snapshotView.alpha = 1
}, completion: { [unowned self] (finished) -> Void in
highlightedSnapshotView.removeFromSuperview()
self.delegate?.collectionView?(self.collectionView as! LxGridView, layout: self, didBeginDraggingItemAtIndexPath: self._movingItemIndexPath!)
})
invalidateLayout()
case .Ended:
fallthrough
case .Cancelled:
_displayLink?.invalidate()
_displayLink = nil
if let movingItemIndexPath = _movingItemIndexPath {
delegate?.collectionView?(collectionView as! LxGridView, layout: self, willEndDraggingItemAtIndexPath: movingItemIndexPath)
_movingItemIndexPath = nil
_sourceItemCollectionViewCellCenter = CGPointZero
let movingItemCollectionViewLayoutAttributes = layoutAttributesForItemAtIndexPath(movingItemIndexPath)
_longPressGestureRecognizer.enabled = false
UIView.animateWithDuration(0, delay: 0, options: .BeginFromCurrentState, animations: { [unowned self] () -> Void in
self._beingMovedPromptView!.center = movingItemCollectionViewLayoutAttributes.center
}, completion: { [unowned self] (finished) -> Void in
self._longPressGestureRecognizer.enabled = true
self._beingMovedPromptView?.removeFromSuperview()
self._beingMovedPromptView = nil
self.invalidateLayout()
self.delegate?.collectionView?(self.collectionView as! LxGridView, layout: self, didEndDraggingItemAtIndexPath: movingItemIndexPath)
})
}
default:
break
}
}
func panGestureRecognizerTriggerd(pan: UIPanGestureRecognizer) {
switch pan.state {
case .Began:
fallthrough
case .Changed:
let panTranslation = pan.translationInView(collectionView!)
_beingMovedPromptView?.center = _sourceItemCollectionViewCellCenter + panTranslation
let sourceIndexPath = _movingItemIndexPath
let destinationIndexPath = collectionView?.indexPathForItemAtPoint((_beingMovedPromptView?.center)!)
if destinationIndexPath == nil || destinationIndexPath == sourceIndexPath {
return
}
if dataSource?.collectionView?(collectionView as! LxGridView, itemAtIndexPath: sourceIndexPath!, canMoveToIndexPath: destinationIndexPath!) == false {
return
}
dataSource?.collectionView?(collectionView as! LxGridView, itemAtIndexPath: sourceIndexPath!, willMoveToIndexPath: destinationIndexPath!)
_movingItemIndexPath = destinationIndexPath
collectionView?.performBatchUpdates({ [unowned self] () -> Void in
self.collectionView?.deleteItemsAtIndexPaths([sourceIndexPath!])
self.collectionView?.insertItemsAtIndexPaths([destinationIndexPath!])
}, completion: { [unowned self] (finished) -> Void in
self.dataSource?.collectionView?(collectionView as! LxGridView, itemAtIndexPath: sourceIndexPath!, didMoveToIndexPath: destinationIndexPath!)
})
default:
break
}
}
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if _panGestureRecognizer == gestureRecognizer && editing {
return _movingItemIndexPath != nil
}
return true
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if _longPressGestureRecognizer == gestureRecognizer {
return _panGestureRecognizer == otherGestureRecognizer
}
if _panGestureRecognizer == gestureRecognizer {
return _longPressGestureRecognizer == otherGestureRecognizer
}
return false
}
// MARK:- displayLink
func displayLinkTriggered(displayLink: CADisplayLink) {
if _remainSecondsToBeginEditing <= 0 {
editing = true
_displayLink?.invalidate()
_displayLink = nil
}
_remainSecondsToBeginEditing = _remainSecondsToBeginEditing - 0.1
}
// MARK:- KVO and notification
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if keyPath == "collectionView" {
if collectionView != nil {
addGestureRecognizers()
}
else {
removeGestureRecognizers()
}
}
}
func applicationWillResignActive(notificaiton: NSNotification) {
_panGestureRecognizer.enabled = false
_panGestureRecognizer.enabled = true
}
}
private func == (left: NSIndexPath, right: NSIndexPath) -> Bool {
return left.section == right.section && left.item == right.item
}
func + (point: CGPoint, offset: CGPoint) -> CGPoint {
return CGPoint(x: point.x + offset.x, y: point.y + offset.y)
}