'swift - ios - set icon and colors on UISwitch

I want to achieve something like this(without the red dots):

enter image description here

What I get:

enter image description here

I have tried the snippet above but the image is repeated several times instead just show it once.

myswitch.thumbTintColor = UIColor(patternImage:UIImage(named:"myimage")!)


Solution 1:[1]

https://medium.com/@milenko_52829/making-custom-uiswitch-part-1-cc3ab9c0b05b

You can refer this tutorial for making custom UISwitch of your own without depending on third party libraries.

In that tutorial, at the setupUI() function, they are assigning a custom view as the thumbView. So in that function create a UIImageView (say myThumbImageView), add your image to that imageView and add the imageView as a subview to the self.thumbView

So your code will be

func setupUI() {
    self.clear()
    self.clipsToBounds = false
    self.thumbView.backgroundColor = self.thumbTintColor
    self.thumbView.isUserInteractionEnabled = false

    let imageName = "yourImage.png"
    let image = UIImage(named: imageName)
    let myThumbImageView = UIImageView(image: image!)
    myThumbImageView.frame = CGRect(x: 0, y: 0, width: self.thumbView.bounds.size.height, height: self.thumbView.bounds.height)
    self.thumbView.addSubview(self.myThumbImageView)

    self.addSubview(self.thumbView)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vincent Joy