Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize uiswitch image properly?

I have an UISwitch in my iOS 6 app, that's on and off image is customised.

self.testSwitch.onImage = [UIImage imageNamed:@"on"]; 
self.testSwitch.offImage = [UIImage imageNamed:@"off"];

I use 77 points wide and 22 points tall image for this purpose (154x44 in retina), as it is stated in the documentation. But my image does not fit to my uiswitch, it seems ugly, the default style hides my one, like on the attached image.

enter image description here

What should I set to make it work in a proper way?

like image 343
Tom Avatar asked Feb 17 '23 14:02

Tom


2 Answers

Here is code from my book. This is not exactly what you want to do, but it shows the technique and will get you started! Notice that I'm using 79 by 27 (not sure where you got your numbers from):

UIGraphicsBeginImageContextWithOptions(CGSizeMake(79,27), NO, 0);
[[UIColor blackColor] setFill];
UIBezierPath* p = [UIBezierPath bezierPathWithRect:CGRectMake(0,0,79,27)];
[p fill];
NSMutableParagraphStyle* para = [NSMutableParagraphStyle new];
para.alignment = NSTextAlignmentCenter;
NSAttributedString* att =
    [[NSAttributedString alloc] initWithString:@"YES" attributes:
        @{
            NSFontAttributeName:[UIFont fontWithName:@"GillSans-Bold" size:16],
            NSForegroundColorAttributeName:[UIColor whiteColor],
            NSParagraphStyleAttributeName:para
        }];
[att drawInRect:CGRectMake(0,5,79,22)];
UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.sw2.onImage = im;

Looks like this:

enter image description here

like image 182
matt Avatar answered Feb 24 '23 08:02

matt


Apple doesn't have an Appearance API for UISwitch. You can set a tint color property (onTintColor). But that's not what you want, I guess. The problem about customizing UISwitch is that there's the opportunity that Apple will reject your app.

But there are some APIs for a custom switch such as RCSwitch(https://github.com/robertchin/rcswitch) or TTSwitch. A good tutorial and example of how to use RCSwitch can be found here: http://www.raywenderlich.com/23424/photoshop-for-developers-creating-a-custom-uiswitch.

like image 30
tobs Avatar answered Feb 24 '23 06:02

tobs