7

I'm new to iOS, while i'm trying to add on/off images to UISwitch in the UIStoryboard, it's not working. It is deprecated in iOS 10. I tried through code also but it's not working.

elseSwitch.onImage = UIImage(named: "switchOff")
elseSwitch.offImage = UIImage(named: "switchOff")
shim
  • 9,289
  • 12
  • 69
  • 108
Joe
  • 859
  • 2
  • 10
  • 27
  • i have a code but in objective c not in swift – Dishant Rajput Nov 24 '16 at 11:20
  • 1
    Possible duplicate of [Why UISwitch onImage/offImage properties are not working on iOS 7?](http://stackoverflow.com/questions/22843747/why-uiswitch-onimage-offimage-properties-are-not-working-on-ios-7) – James P Nov 24 '16 at 11:22
  • 1
    Possible duplicate of [Custom On/Off Image iOS 7.0 UI Switch](http://stackoverflow.com/questions/19410300/custom-on-off-image-ios-7-0-ui-switch) – Ashish Kakkad Nov 24 '16 at 11:26
  • You have set both states to `switchOff ` ... do you have a `switchOn` Image? – Wez Nov 24 '16 at 11:39
  • In iOS 6 and earlier, the image displayed when the switch is in the on/off position. – IKKA Nov 06 '17 at 08:32

1 Answers1

13

onImage and offImage has no effect on UISwitch anymore as you've discovered :)

Instead you can use

  • onTintColor to set the tint color of the switch when it is turned on.
  • tintColor to set the tint color of the switch when it is turned off.
  • thumbTintColor to set the tint color of the thumb.

You can read more about it here

Here is an example using those three properties:

@IBOutlet weak var toggleSwitch: UISwitch! {
    didSet {
        toggleSwitch.isOn = true
        toggleSwitch.tintColor = UIColor.red
        toggleSwitch.onTintColor = UIColor.blue
        toggleSwitch.thumbTintColor = UIColor.brown
    }
}

Which gives me this beautiful switch when turned off

off switch

And this when turned on

on switch

(I'm a developer not a designer if you can't tell ;))

So in your case you could use some shade of grey for the onTintColor and tintColor to get you to this result

enter image description here

enter image description here

Hope that helps you.

pbodsk
  • 6,787
  • 3
  • 21
  • 51