-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathCustomUISwitch.swift
60 lines (48 loc) · 1.51 KB
/
CustomUISwitch.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
//
// CustomUISwitch.swift
// Lockdown
//
// Created by Aliaksandr Dvoineu on 26.04.23.
// Copyright © 2023 Confirmed Inc. All rights reserved.
//
import UIKit
import CoreMotion
final class CustomUISwitch: UIButton {
var status: Bool = false {
didSet {
self.update()
}
}
var onImage: UIImage?
var offImage: UIImage?
init(onImage: UIImage, offImage: UIImage) {
self.onImage = onImage
self.offImage = offImage
super.init(frame: CGRect.zero)
self.setStatus(false)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update() {
UIView.transition(with: self, duration: 0.10, options: .transitionCrossDissolve, animations: {
self.status ? self.setImage(self.onImage, for: .normal) : self.setImage(self.offImage, for: .normal)
}, completion: nil)
}
func toggle() {
self.status ? self.setStatus(false) : self.setStatus(true)
}
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()
}
func sendHapticFeedback() {
let impactFeedbackgenerator = UIImpactFeedbackGenerator(style: .heavy)
impactFeedbackgenerator.prepare()
impactFeedbackgenerator.impactOccurred()
}
}