forked from amirdew/CollectionViewPagingLayout
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuantityControllerView.swift
More file actions
87 lines (68 loc) · 2.72 KB
/
QuantityControllerView.swift
File metadata and controls
87 lines (68 loc) · 2.72 KB
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
//
// QuantityControllerView.swift
// CollectionViewPagingLayout
//
// Created by Amir Khorsandi on 12/26/19.
// Copyright © 2019 Amir Khorsandi. All rights reserved.
//
import UIKit
protocol QuantityControllerViewDelegate: class {
func onIncreaseButtonTouched(view: QuantityControllerView)
func onDecreaseButtonTouched(view: QuantityControllerView)
}
class QuantityControllerView: UIView, NibBased {
// MARK: Properties
var quantity: Int = 0 { didSet { updateQuantity() } }
weak var delegate: QuantityControllerViewDelegate?
@IBOutlet private weak var container: UIView!
@IBOutlet private weak var quantityLabel: UILabel!
@IBOutlet private weak var increaseButton: UIButton!
@IBOutlet private weak var decreaseButton: UIButton!
// MARK: Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
quantityLabel.font = .systemFont(ofSize: 31, weight: .semibold)
quantityLabel.textColor = UIColor.black.withAlphaComponent(0.69)
updateQuantity()
}
// MARK: Listeners
@IBAction private func onButtonTouched(sender: UIButton) {
if sender == increaseButton {
animateButtonTouch(isDecrease: false)
delegate?.onIncreaseButtonTouched(view: self)
}
if sender == decreaseButton {
animateButtonTouch(isDecrease: true)
delegate?.onDecreaseButtonTouched(view: self)
}
}
// MARK: Private functions
private func updateQuantity() {
quantityLabel.text = "\(quantity)"
}
private func animateButtonTouch(isDecrease: Bool, reset: Bool = false) {
let timing = CAMediaTimingFunction(name: reset ? .easeIn : .easeOut)
let animation: CABasicAnimation = CABasicAnimation(keyPath: "transform")
var newTransform = CATransform3DIdentity
newTransform.m34 = -0.004
newTransform = CATransform3DRotate(newTransform, (isDecrease ? -1 : 1) * .pi / 6, 0, 1, 0)
CATransaction.begin()
if !reset {
CATransaction.setCompletionBlock { [weak self] in
self?.animateButtonTouch(isDecrease: isDecrease, reset: true)
}
}
CATransaction.setAnimationTimingFunction(timing)
animation.duration = 0.18
if reset {
animation.fromValue = newTransform
animation.toValue = CATransform3DIdentity
} else {
animation.fromValue = CATransform3DIdentity
animation.toValue = newTransform
}
container.layer.transform = (animation.toValue as? CATransform3D)!
container.layer.add(animation, forKey: nil)
CATransaction.commit()
}
}