I have created a switch class named ImageSwitch (You can simply download and drag and drop that class into your code or you can refer below)
import UIKit
class ImageSwitch: UISwitch {
@IBInspectable var thumbImage: UIImage? {
didSet {
updateView()
}
}
var thumbSize = CGSize.zero
var onPoint = CGPoint.zero
var offPoint = CGPoint.zero
var imageView: UIImageView?
func updateView() {
if let thumbImage = thumbImage {
imageView = UIImageView(image: thumbImage)
imageView?.backgroundColor = .white
imageView?.contentMode = .center
thumbSize = CGSize(width: self.bounds.size.height - 2, height: self.bounds.height - 2)
let yPostition = (self.bounds.size.height - thumbSize.height) / 2
onPoint = CGPoint(x: self.bounds.size.width - thumbSize.width - 1, y: yPostition)
offPoint = CGPoint(x: 1, y: yPostition)
imageView?.frame = CGRect(origin: offPoint, size: thumbSize)
imageView?.layer.cornerRadius = thumbSize.height * 0.5
self.addSubview(imageView ?? UIImageView(image: thumbImage))
}
}
func updateThumbPosition() {
DispatchQueue.main.async {
self.imageView?.frame = CGRect(origin: self.isOn ? self.onPoint : self.offPoint, size: self.thumbSize)
}
}
}
Add an UISwitch to the storyboard and assign its Custom Class to ImageSwitch. Assign the image you want to set as a thumb image to switch.
Add IBOutlet of the same in your viewController and add its target for the valueChanged event and call ImageSwitch’s updateThumbPosition() to update the position of the thumb(as its name suggests) whenever the user clicks on the switch to turn it off/on.
imageSwitch.addTarget(self, action: #selector(switchValueDidChange(_:)), for: .valueChanged)
@objc func switchValueDidChange(_ sender: ImageSwitch!) {
sender.updateThumbPosition()
//Other things you want to do....
}
And that's it! You can also check the same here.