Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift - ios - set icon and colors on UISwitch

Tags:

swift

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")!)
like image 694
Ricardo Avatar asked Nov 17 '25 04:11

Ricardo


1 Answers

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)
}
like image 140
Vincent Joy Avatar answered Nov 18 '25 21:11

Vincent Joy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!