-
Notifications
You must be signed in to change notification settings - Fork 1
/
SwitchButton.swift
94 lines (77 loc) · 2.42 KB
/
SwitchButton.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
//
// Created by SampleDemo
// Copyright © SampleDemo All rights reserved.
// Created on 31/07/20
import UIKit
import CoreMotion
protocol SwitchButtonDelegate: class {
func valueChangeEvent(isOn: Bool)
}
@IBDesignable class SwitchButton: UIButton {
/// By default set the true
@IBInspectable var isOn: Bool = true {
didSet {
setStatus(isOn)
}
}
/// set off status image
@IBInspectable var offImage: UIImage? {
didSet {
setStatus(isOn)
}
}
/// set on status image
@IBInspectable var onImage: UIImage? {
didSet {
setStatus(isOn)
}
}
public weak var delegate: SwitchButtonDelegate?
/// Status On/Off
private(set) var status: Bool = false {
didSet {
self.update()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setStatus(false)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Update the Button Image base on status
private func update() {
guard let onImage = self.onImage else { return }
guard let offImage = self.offImage else { return }
UIView.transition(with: self, duration: 0.50, options: .transitionCrossDissolve, animations: { [weak self] in
guard let self = self else { return }
self.status ? self.setImage(onImage, for: .normal) : self.setImage(offImage, for: .normal)
}, completion: nil)
}
/// Toggle the value
private func toggle() {
status ? setStatus(false) : setStatus(true)
delegate?.valueChangeEvent(isOn: self.status)
}
/// Set the Switch On/Off Status
/// - Parameter status: on/off value
public func setStatus(_ status: Bool) {
self.status = status
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
self.sendHapticFeedback()
self.toggle()
}
/// Haptic Feedback For Touch Feel
private func sendHapticFeedback() {
let impactFeedbackgenerator = UIImpactFeedbackGenerator(style: .heavy)
impactFeedbackgenerator.prepare()
impactFeedbackgenerator.impactOccurred()
}
}
// MARK: - SwitchButtonDelegate
extension SwitchButton: SwitchButtonDelegate {
func valueChangeEvent(isOn: Bool) { }
}