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. You need to add the below pod in your project for Animated Custom Switch.
1 |
pod 'DDAnimatedSwitch' |
2. Please import the library in your controller.
1 |
import DDAnimatedSwitch |
3. Add view in your storyboard like
1 |
@IBOutlet weak var switchView : UIView! |
4. Initiate custom switch view in your controller
var bigSwitch: DDSwitch?
5. Please create a new file and write animation code as below
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") } } |
6. Add the animation image .plist file like below
This is the animation plist file and your images in image assest
7. Add protocol for the switch
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() } } } |
8. Add the below code in your view controller.
If you have done every things correctly which is mentioned above you will get the output as below.
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.