forked from seedante/CardAnimation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCardAnimationView.swift
536 lines (448 loc) · 19.4 KB
/
CardAnimationView.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//
// AnimatedCardsView.swift
// CardAnimation
//
// Created by Luis Sanchez Garcia on 14/10/15.
// Copyright © 2015 seedante. All rights reserved.
//
import UIKit
protocol CardView {
func contentVisible(visible:Bool)
func prepareForReuse()
}
public class BaseCardView: UIView, CardView {
func contentVisible(visible:Bool) { }
func prepareForReuse() { }
}
public protocol CardAnimationViewDataSource : class {
func numberOfVisibleCards() -> Int
func numberOfCards() -> Int
/**
Ask the delegate for a new card to display in the container.
- parameter number: number that is needed to be displayed.
- parameter reusedView: the component may provide you with an unused view.
- returns: correctly configured card view.
*/
func cardNumber(number:Int, reusedView:BaseCardView?) -> BaseCardView
}
/// View to display a list of cards featuring a flipping up and down animation effect.
public class CardAnimationView: UIView {
// MARK: Public properties
/// Data source delegate, class won't work until it's set.
public weak var dataSourceDelegate : CardAnimationViewDataSource? {
didSet { // Only start to work if delegate is set
if dataSourceDelegate != nil {
configure()
}
}
}
/// Animation speed for the cards animations.
public var animationsSpeed = 0.2
/// Defines the card size that will be used. (width, height)
public var cardSize : (width:CGFloat, height:CGFloat) {
didSet { // Only reset when delegate is set
if dataSourceDelegate != nil {
configure()
}
}
}
// MARK: Private properties
private struct Constants {
struct CardDefaultSize {
static let width : CGFloat = 400.0
static let height : CGFloat = 300.0
}
}
private var cardArray : [BaseCardView]! = []
private var poolCardArray : [BaseCardView]! = []
private lazy var gestureRecognizer : UIPanGestureRecognizer = {
return UIPanGestureRecognizer(target: self, action: "scrollOnView:")
}()
private struct PrivateConstants {
static let maxVisibleCardCount = 8
static let cardCount = 8
}
private var cardCount = PrivateConstants.cardCount
private var maxVisibleCardCount = PrivateConstants.maxVisibleCardCount
private var gestureDirection:panScrollDirection = .Up
private var gestureTempCard: BaseCardView?
private var currentIndex = 0
private lazy var flipUpTransform3D : CATransform3D = {
var transform = CATransform3DIdentity
transform.m34 = -1.0 / 1000.0
transform = CATransform3DRotate(transform, 0, 1, 0, 0)
return transform
}()
private lazy var flipDownTransform3D : CATransform3D = {
var transform = CATransform3DIdentity
transform.m34 = -1.0 / 1000.0
transform = CATransform3DRotate(transform, CGFloat(-M_PI), 1, 0, 0)
return transform
}()
// MARK: Initializers
/**
Initializes a view object with the specified frame rectangle.
- parameter frame: adssad
*/
override init(frame: CGRect) {
cardSize = (Constants.CardDefaultSize.width, Constants.CardDefaultSize.height)
super.init(frame: frame)
}
/**
Initializes a view object from data in a given unarchiver.
- parameter coder: An unarchiver object.
*/
required public init?(coder aDecoder: NSCoder) {
cardSize = (Constants.CardDefaultSize.width, Constants.CardDefaultSize.height)
super.init(coder: aDecoder)
}
// MARK: Config
private func configure() {
configureConstants()
generateCards()
addGestureRecognizer(gestureRecognizer)
self.relayoutSubViewsAnimated(false)
}
private func configureConstants() {
maxVisibleCardCount = self.dataSourceDelegate?.numberOfVisibleCards() ?? PrivateConstants.maxVisibleCardCount
cardCount = self.dataSourceDelegate?.numberOfCards() ?? PrivateConstants.cardCount
}
// MARK: Public
/// Reloads the cards of the animated cards view.
public func reloadData() {
configure()
}
/**
Flips up one card with animation
- returns: if the action was performed or not (out of bounds)
*/
public func flipUp() -> Bool {
guard currentIndex > 0 else {
return false
}
currentIndex--
let newView = addNewCardViewWithIndex(currentIndex)
newView.layer.transform = flipDownTransform3D
let shouldRemoveLast = cardArray.count > maxVisibleCardCount
UIView.animateKeyframesWithDuration(animationsSpeed, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1, animations: {
newView.layer.transform = self.flipUpTransform3D
})
UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.01, animations: {
newView.contentVisible(true)
})
}, completion: { _ in
self.relayoutSubViewsAnimated(true, removeLast: shouldRemoveLast)
})
return true
}
/**
Flips down one card with animation
- returns: if the action was performed or not (out of bounds)
*/
public func flipDown() -> Bool {
guard currentIndex < cardCount else {
return false
}
currentIndex++
let frontView = cardArray.removeFirst()
let lastIndex = currentIndex + cardArray.count
if lastIndex < cardCount {
addNewCardViewWithIndex(lastIndex, insertOnRear: true)
}
UIView.animateKeyframesWithDuration(animationsSpeed*1.5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1, animations: {
frontView.layer.transform = self.flipDownTransform3D
})
UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.01, animations: {
frontView.contentVisible(false)
})
}, completion: { _ in
self.poolCardArray.append(frontView)
frontView.removeFromSuperview()
self.relayoutSubViewsAnimated(true)
})
return true
}
}
// MARK: Pan gesture
extension CardAnimationView {
@objc private func scrollOnView(gesture: UIPanGestureRecognizer) {
let velocity = gesture.velocityInView(self)
let percent = gesture.translationInView(self).y/150
var flipTransform3D = CATransform3DIdentity
flipTransform3D.m34 = -1.0 / 1000.0
switch gesture.state{
case .Began:
gestureDirection = velocity.y > 0 ? .Down : .Up
case .Changed:
if gestureDirection == .Down{ // Flip down
guard currentIndex < cardCount else {
gesture.enabled = false // Cancel gesture
return
}
let frontView = cardArray[0]
switch percent{
case 0.0..<1.0:
flipTransform3D = CATransform3DRotate(flipTransform3D, CGFloat(-M_PI) * percent, 1, 0, 0)
frontView.layer.transform = flipTransform3D
if percent >= 0.5{
frontView.contentVisible(false)
}else{
frontView.contentVisible(true)
}
case 1.0...CGFloat(MAXFLOAT):
flipTransform3D = CATransform3DRotate(flipTransform3D, CGFloat(-M_PI), 1, 0, 0)
frontView.layer.transform = flipTransform3D
default:
print(percent)
}
} else { // Flip up
guard currentIndex > 0 else {
gesture.enabled = false // Cancel gesture
return
}
if gestureTempCard == nil {
let newView = addNewCardViewWithIndex(currentIndex-1)
newView.layer.transform = flipDownTransform3D
gestureTempCard = newView
}
switch percent{
case CGFloat(-MAXFLOAT)...(-1.0):
gestureTempCard!.layer.transform = CATransform3DIdentity
case -1.0...0:
if percent <= -0.5{
gestureTempCard!.contentVisible(true)
}else{
gestureTempCard!.contentVisible(false)
}
flipTransform3D = CATransform3DRotate(flipTransform3D, CGFloat(-M_PI) * (percent+1.0), 1, 0, 0)
gestureTempCard!.layer.transform = flipTransform3D
default:
print(percent)
}
}
case .Ended:
switch gestureDirection{
case .Down:
if percent >= 0.5{
currentIndex++
let frontView = cardArray.removeFirst()
let lastIndex = currentIndex + cardArray.count
if lastIndex < cardCount {
addNewCardViewWithIndex(lastIndex, insertOnRear: true)
}
flipTransform3D = CATransform3DRotate(flipTransform3D, CGFloat(M_PI), 1, 0, 0)
UIView.animateWithDuration(0.3, animations: {
frontView.layer.transform = flipTransform3D
}, completion: {
_ in
self.poolCardArray.append(frontView)
frontView.removeFromSuperview()
self.relayoutSubViewsAnimated(true)
})
}else{
let frontView = cardArray[0]
UIView.animateWithDuration(0.2, animations: {
frontView.layer.transform = CATransform3DIdentity
})
}
case .Up:
guard currentIndex > 0 else {
return
}
if percent <= -0.5{
currentIndex--
let shouldRemoveLast = cardArray.count > maxVisibleCardCount
UIView.animateWithDuration(0.2, animations: {
self.gestureTempCard!.layer.transform = CATransform3DIdentity
}, completion: {
_ in
self.relayoutSubViewsAnimated(true, removeLast: shouldRemoveLast)
self.gestureTempCard = nil
})
}else{
UIView.animateWithDuration(0.2, animations: {
self.gestureTempCard!.layer.transform = CATransform3DRotate(flipTransform3D, CGFloat(-M_PI), 1, 0, 0)
}, completion: {
_ in
self.poolCardArray.append(self.gestureTempCard!)
self.cardArray.removeFirst()
self.gestureTempCard!.removeFromSuperview()
self.gestureTempCard = nil
})
}
}
case .Cancelled: // When cancel reenable gesture
gesture.enabled = true
default:
print("DEFAULT: DO NOTHING")
}
}
}
// MARK: Card Generation
extension CardAnimationView {
private func generateCards() {
// Clear previous configuration
if cardArray.count > 0 {
for view in cardArray {
view.removeFromSuperview()
}
}
cardArray = (0..<maxVisibleCardCount).map { (index) in
let view = generateNewCardViewWithIndex(index)
addSubview(view)
applyConstraintsToView(view)
return view
}
poolCardArray = []
}
private func addNewCardViewWithIndex(index:Int, insertOnRear rear:Bool = false) -> BaseCardView {
let newIndex = rear ? subviews.count : 0
var newView : BaseCardView?
// Reuse cards
if poolCardArray.count > 0 {
let reusedView = poolCardArray.removeFirst()
newView = generateNewCardViewWithIndex(index, reusingCardView: reusedView)
} else {
newView = generateNewCardViewWithIndex(index)
}
rear ? insertSubview(newView!, atIndex: newIndex) : addSubview(newView!)
rear ? cardArray.append(newView!) : cardArray.insert(newView!, atIndex: newIndex)
applyConstraintsToView(newView!)
relayoutSubView(newView!, relativeIndex: newIndex, animated: false)
newView!.alpha = rear ? 0.0 : 1.0
return newView!
}
private func generateNewCardViewWithIndex(index:Int, reusingCardView cardView:BaseCardView? = nil) -> BaseCardView {
// Reset card
if cardView != nil {
cardView!.layer.transform = flipUpTransform3D
cardView!.removeConstraints(cardView!.constraints)
cardView!.prepareForReuse()
}
let view = self.dataSourceDelegate!.cardNumber(index, reusedView: cardView)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}
private func applyConstraintsToView(view:UIView) {
view.addConstraints([
NSLayoutConstraint(item: view, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: CGFloat(1.0), constant: cardSize.width),
NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: CGFloat(1.0), constant: cardSize.height),
])
view.superview!.addConstraints([
NSLayoutConstraint(item: view, attribute: .CenterX, relatedBy: .Equal, toItem: view.superview, attribute: .CenterX, multiplier: CGFloat(1.0), constant: 0),
NSLayoutConstraint(item: view, attribute: .CenterY, relatedBy: .Equal, toItem: view.superview, attribute: .CenterY, multiplier: CGFloat(1.0), constant: 0),
])
}
}
// MARK: Handle Layout
extension CardAnimationView {
private func relayoutSubView(subView:BaseCardView, relativeIndex:Int, animated:Bool = true, delay: NSTimeInterval = 0, fadeAndDelete delete: Bool = false) {
let width = cardSize.width
let height = cardSize.height
subView.layer.anchorPoint = CGPointMake(0.5, 1)
subView.layer.zPosition = CGFloat(1000 - relativeIndex)
let sizeScale = calculateWidthScaleForIndex(relativeIndex)
let filterWidthSubViewConstraints = subView.constraints.filter({$0.firstAttribute == .Width && $0.secondItem == nil})
if filterWidthSubViewConstraints.count > 0{
let widthConstraint = filterWidthSubViewConstraints[0]
widthConstraint.constant = sizeScale * width
}
let filterHeightSubViewConstraints = subView.constraints.filter({$0.firstAttribute == .Height && $0.secondItem == nil})
if filterHeightSubViewConstraints.count > 0{
let heightConstraint = filterHeightSubViewConstraints[0]
heightConstraint.constant = sizeScale * height
}
let filteredViewConstraints = self.constraints.filter({$0.firstItem as? UIView == subView && $0.secondItem as? UIView == self && $0.firstAttribute == .CenterY})
if filteredViewConstraints.count > 0{
let centerYConstraint = filteredViewConstraints[0]
let subViewHeight = calculateWidthScaleForIndex(relativeIndex) * height
let YOffset = calculusYOffsetForIndex(relativeIndex)
centerYConstraint.constant = subViewHeight/2 - YOffset
}
UIView.animateWithDuration(animated ? animationsSpeed : 0, delay: delay, options: .BeginFromCurrentState, animations: {
subView.alpha = delete ? 0 : self.calculateAlphaForIndex(relativeIndex)
self.layoutIfNeeded()
}, completion: { _ in
if delete {
self.poolCardArray.append(subView)
subView.removeFromSuperview()
}
})
}
private func relayoutSubViewsAnimated(animated:Bool, removeLast remove:Bool = false){
for (index, view) in cardArray.enumerate() {
let shouldDelete = remove && index == cardArray.count-1
let delay = animated ? 0.1 * Double(index) : 0
relayoutSubView(view, relativeIndex: index, delay: delay, fadeAndDelete: shouldDelete)
}
if remove {
cardArray.removeLast()
}
}
//MARK: Helper Methods
//f(x) = k * x + m
private func calculateFactorOfFunction(x1: CGFloat, x2: CGFloat, y1: CGFloat, y2: CGFloat) -> (CGFloat, CGFloat){
let k = (y1-y2)/(x1-x2)
let m = (x1*y2 - x2*y1)/(x1-x2)
return (k, m)
}
private func calculateResult(argument x: Int, k: CGFloat, m: CGFloat) -> CGFloat{
return k * CGFloat(x) + m
}
private func calcuteResultWith(x1: CGFloat, x2: CGFloat, y1: CGFloat, y2: CGFloat, argument: Int) -> CGFloat{
let (k, m) = calculateFactorOfFunction(x1, x2: x2, y1: y1, y2: y2)
return calculateResult(argument: argument, k: k, m: m)
}
//I set the gap between 0Card and 1st Card is 35, gap between the last two card is 15. These value on iPhone is a little big, you could make it less.
//设定头两个卡片的距离为35,最后两张卡片之间的举例为15。不设定成等距才符合视觉效果。
private func calculusYOffsetForIndex(indexInQueue: Int) -> CGFloat{
if indexInQueue < 1{
return CGFloat(0)
}
var sum: CGFloat = 0.0
for i in 1...indexInQueue{
var result = calcuteResultWith(1, x2: 8, y1: 35, y2: 15, argument: i)
if result < 5{
result = 5.0
}
sum += result
}
return sum
}
private func calculateWidthScaleForIndex(indexInQueue: Int) -> CGFloat{
let widthBaseScale:CGFloat = 0.5
var factor: CGFloat = 1
if indexInQueue == 0{
factor = 1
}else{
factor = calculateScaleFactorForIndex(indexInQueue)
}
return widthBaseScale * factor
}
//Zoom out card one by one.
//为符合视觉以及营造景深效果,卡片依次缩小
private func calculateScaleFactorForIndex(indexInQueue: Int) -> CGFloat{
if indexInQueue < 1{
return CGFloat(1)
}
var scale = calcuteResultWith(1, x2: 8, y1: 0.95, y2: 0.5, argument: indexInQueue)
if scale < 0.1{
scale = 0.1
}
return scale
}
private func calculateAlphaForIndex(indexInQueue: Int) -> CGFloat{
if indexInQueue < 1{
return CGFloat(1)
}
var alpha = calcuteResultWith(6, x2: 9, y1: 1, y2: 0.4, argument: indexInQueue)
if alpha < 0.1{
alpha = 0.1
}else if alpha > 1{
alpha = 1
}
return alpha
}
}