Skip to content

Instantly share code, notes, and snippets.

@prabhKaur03
Last active April 6, 2022 13:31
Show Gist options
  • Save prabhKaur03/1eac3d32abef554351ef053009e3d73f to your computer and use it in GitHub Desktop.
Save prabhKaur03/1eac3d32abef554351ef053009e3d73f to your computer and use it in GitHub Desktop.
UISwitch With Thumb Image
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)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment