UISwitch - change from on/off to yes/no

krisdyson picture krisdyson · Dec 1, 2010 · Viewed 46.4k times · Source

does anyone know of a way I can change the text label for on and off to yes and no.

I did it with

            ((UILabel *)[[[[[[switchControl subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:0]).text = @"Yes";
        ((UILabel *)[[[[[[switchControl subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:1]).text = @"No";

However, with the release of iOS 4.2, this is no longer supported (this probably wasn't recommended by Apple anyway)

My client is insisting on yes/no switches. I'd appreciate any advice!

many thanks

Answer

Snips picture Snips · Nov 16, 2012

Hurrah! From iOS 6, it's possible to specify an image to be used for the on / off states, respectively. So, this can be used to display a YES / NO image (or whatever image representing the text you would prefer to use instead of the previously limited ON / OFF).

 if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0"))
 {
     [mySwitch setOnImage: [UIImage imageNamed:@"UISwitch-Yes"]];
     [mySwitch setOffImage:[UIImage imageNamed:@"UISwitch-No"]];
 }

The images should be 77 px wide, 27 px high, and the text (one image for each state) should be horizontally centred within that 77 px width. I use transparent backgrounds for the text, so I can still make use of the tint for the background, which still works with this.

Of course, it would seem easier to just supply text, rather than having to use an image of text, but I'm certainly grateful for this new option, at least.