Reputation: 12444
For the past three days I have been trying to roll my own UISwitch because it is customized with a custom image for the actual switch button and a custom image for the track. So far it has resulted in bugs and ugly code and it just does not work well.
Since I don't want to re-invent the wheel, are there any ways or libraries that I can use that allow me to customize a UISwitch with my own UIImage's?
Upvotes: 0
Views: 6615
Reputation: 7588
I made a custom UISwitch class and I'd like to share it. You can download the custom UISwitch here:
http://xcodenoobies.blogspot.com/2013/04/free-custom-uiswitch-flexible-colors.html
Cheers
Upvotes: 1
Reputation: 7146
You can create a completely custom version of the switch using layers.
Below is a simple example. You should be able to modify this to use Images or whatever custom graphics you feel like drawing.
Instead of the standard looking switch, it uses red and green fill to indicate on/off state. It behaves the same as a `UISwitch, it's just using different graphics. Since we're using CALayer, the color transition is also animated for us.
//CustomSwitch.H
#import <Foundation/Foundation.h>
@interface CustomSwitch : UISwitch {
CALayer* uiLayer;
}
@end
//CustomSwitch.m
#import "CustomSwitch.h"
#import "QuartzCore/QuartzCore.h"
@implementation CustomSwitch
-(id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
[self addTarget:self action:@selector(checked:) forControlEvents:UIControlEventValueChanged];
if (NULL!=self)
{
[self customLayout];
}
return self;
}
-(void) checked:(id) event
{
uiLayer.backgroundColor= [self isOn] ? [UIColor greenColor].CGColor : [UIColor redColor].CGColor;
}
-(void) customLayout
{
uiLayer = [CALayer layer];
uiLayer.frame = self.frame;
uiLayer.backgroundColor= [UIColor redColor ].CGColor;
[[self layer] addSublayer:uiLayer];
}
-(void)dealloc
{
[uiLayer release];
}
@end
Upvotes: 2
Reputation:
This is an almost-complete UISwitch-like control. Since it's opensource, you can subclass/modify it in order to customize it using images.
https://github.com/domesticcatsoftware/DCRoundSwitch
Upvotes: 2