Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISwitch set on/off Image

I want to set my Switch like this:

enter image description here

But I try in ios9 , it does not work. I saw in apple UISwitch Class Reference. It says that :

Discussion In iOS 7, this property has no effect.

How about iOS 9? Any one success?

My Code:

switch1 = UISwitch(frame:CGRectMake(self.view.frame.width/2 - 20, 400, 10, 100))
switch1.on = true
switch1.onTintColor = UIColor.lightGrayColor()
switch1.tintColor = UIColor.greenColor()
switch1.thumbTintColor = UIColor.blackColor()

//set on/off image

switch1.onImage = UIImage(named: "on-switch")
switch1.offImage = UIImage(named: "off-switch")
like image 466
YungCheng Su Avatar asked Apr 29 '16 03:04

YungCheng Su


Video Answer


2 Answers

For iOS 13, you could do this way:

   let switcher = UISwitch()
    switcher.addTarget(self, action: #selector(pressed), for: .valueChanged)
    

 @objc func pressed(sender: UISwitch) {
        let color = UIColor(patternImage: UIImage(named: sender.isOn ? "on.png": "off.png")!)
        if sender.isOn {
            sender.onTintColor = color
        } else {
            sender.tintColor = color
            sender.subviews[0].subviews[0].backgroundColor = color
        }
    }

NOTE: your image should look like:

enter image description here

Then the final result is:

enter image description here

like image 177
William Hu Avatar answered Nov 15 '22 19:11

William Hu


Use a UIButton instead.

let switchButton = UIButton(type: .Custom)
switchButton.selected = true
switchButton.setImage(UIImage(named: "on-switch"), forState: .Selected)
switchButton.setImage(UIImage(named: "off-switch"), forState: .Normal)

Use switchButton.isSelected instead of switch1.on. You'll have to toggle switchButton.isSelected when it is tapped, which you can do like this:

switchButton.isSelected.toggle()
like image 23
rob mayoff Avatar answered Nov 15 '22 21:11

rob mayoff