UISwitch with Thumb Image

Prabh Kaur
2 min readApr 7, 2022
Photo by Isaac Li Shung Tan on Unsplash

Do you have a similar requirement like above? Then you have landed on the right page.

From many ways of doing that, I have found a very simple and elegant solution to do this. So without any delay let’s jump directly into the coding part.

First of all, I have created a switch class named ‘ImageSwitch’ (You can simply drag and drop that class into your code) with IBInspectable property ‘thumbImage’ that can help us to set thumb image for UISwitch from the storyboard.

class ImageSwitch: UISwitch {        
@IBInspectable var thumbImage: UIImage? {
didSet {
updateView()
}
}
}

Next, 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.

// MARK: - Outlets@IBOutlet var imageSwitch: ImageSwitch!override func viewDidLoad() {super.viewDidLoad()imageSwitch.addTarget(self, action: #selector(switchValueDidChange(_:)), for: .valueChanged)}

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.

@objc func switchValueDidChange(_ sender: ImageSwitch!) {sender.updateThumbPosition()
//Other things you want to do....
}

And that’s it! Now you have your own UISwitch with any image you want on its thumb.

Pretty simple, right? Go on and play with it.

Happy Coding!!! 😁

--

--