-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUISpringyButton.swift
More file actions
98 lines (78 loc) · 2.9 KB
/
Copy pathUISpringyButton.swift
File metadata and controls
98 lines (78 loc) · 2.9 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
88
89
90
91
92
93
94
95
96
97
98
//
// UISpringyButton.swift
// v1.0
//
// Created by Andy Peatling
// https://apeatling.com
//
import Foundation
import UIKit
class UISpringyButton: UIButton {
private var animator = UIViewPropertyAnimator()
private var originalFrame:CGRect!
private let normalColor = UIColor.clear
private let highlightedColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.15)
private let animationDelay = 0.2
private var longPress = false
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
func sharedInit() {
self.originalFrame = self.frame
addTarget(self, action: #selector(touchDown), for: [.touchDown, .touchDragEnter])
addTarget(self, action: #selector(touchUp), for: [.touchUpInside, .touchCancel])
addTarget(self, action: #selector(dragExit), for: [.touchDragExit])
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
longPress.cancelsTouchesInView = false
self.addGestureRecognizer(longPress)
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.width / 2
imageView?.contentMode = .center
}
@objc private func touchDown() {
self.animator.stopAnimation(true)
self.depressButton(scaleX: 0.9, scaleY: 0.9)
DispatchQueue.main.asyncAfter(deadline: .now() + self.animationDelay) {
self.animator.startAnimation()
}
}
@objc private func touchUp() {
if !self.longPress {
self.depressButton(scaleX: 0.85, scaleY: 0.85)
self.animator.startAnimation()
}
self.releaseButton()
self.longPress = false
}
@objc private func dragExit() {
self.releaseButton()
}
@objc private func longPress(_ gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizer.State.began {
self.longPress = true
}
}
private func depressButton(scaleX: CGFloat, scaleY: CGFloat) {
self.animator = UIViewPropertyAnimator(duration: 0.2, curve: .easeInOut, animations: {
self.backgroundColor = self.highlightedColor
self.imageView?.transform = CGAffineTransform(scaleX: scaleX, y: scaleY)
})
}
private func releaseButton() {
self.animator = UIViewPropertyAnimator(duration: 0.2, curve: .easeInOut, animations: {
self.backgroundColor = self.normalColor
self.transform = .identity
self.imageView?.transform = .identity
})
DispatchQueue.main.asyncAfter(deadline: .now() + self.animationDelay) {
self.animator.startAnimation()
}
}
}