Updated 28 February 2022
Hello, In this blog we are going to learn about how to use or build an Animated Custom Switch
In the UISwitch you cannot edit the switch, so we need to create an Animated Custom Switch by any 3rd party library or on your own. In this blog, we are using a third party library
1 |
pod 'DDAnimatedSwitch' |
1 |
import DDAnimatedSwitch |
1 |
@IBOutlet weak var switchView : UIView! |
var bigSwitch: DDSwitch?
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 |
import Foundation import DDAnimatedSwitch class CustomSwitch: DDAnimatedSwitch, PreviewDDSwitchProtocol { override init(frame: CGRect) { super.init(frame: frame) cornerRadius = 0.5 thumbTintColor = UIColor.clear padding = frame.size.height / 8 let side = frame.size.height - 2 * padding thumbSize = CGSize(width: side, height: side) duration = 0.8 thumbAnimationName = "volumeAnimation" backgroundAnimationName = "SpaceBackAnimation" // just for preview isPreview = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } |
This is the animation plist file and your images in image assest
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 |
import Foundation import DDAnimatedSwitch protocol PreviewDDSwitchProtocol: class { var isPreview: Bool { get set } } extension PreviewDDSwitchProtocol where Self: DDSwitch { var isPreview: Bool { get { return false } set { if newValue == true { DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in self?.changeSwitch() } } } } func changeSwitch() { isOn = !isOn DispatchQueue.main.asyncAfter(deadline: .now() + 0.2 + Double(duration)) { [weak self] in self?.changeSwitch() } } } |
Thank you for reading this article. After that, if you want to read more articles regarding iOS Development click here or if you want to read more about custom switch click here.
I hope this blog will help you to implement a custom switch, if you have any queries, comments, questions, or recommendations, feel free to post them in the comment section below!
if you want to read more about custom switches click here.
For other technical blogs, please click here.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.