iOS SDK中的UISwitch不可以改变它的文本和颜色,如果想用这个控件作为男女性别选择的话,就要自定义UISwitch了。
可以在xib中拖入一个UISlider,并将它的Class改成UICustomSwitch,为什么是拖入一个UISlider,而不是UISwitch呢?因为,自定义的类UICustomSwitch是继承UISlider的。
ViewController.h
#import <UIKit/UIKit.h> #import "UICustomSwitch.h" @interface ViewController : UIViewController{ IBOutlet UICustomSwitch *custom_switch; } @end
ViewController.m
#import "ViewController.h" @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; custom_switch.leftLabel.text = @"男"; custom_switch.rightLabel.text = @"女"; custom_switch.tintColor = [UIColor brownColor]; custom_switch.frame = CGRectMake(custom_switch.frame.origin.x, custom_switch.frame.origin.y, 95, 27); } @end
也可以直接通过代码创建。
- (void)viewDidLoad { [super viewDidLoad]; UICustomSwitch *custom_switch = [UICustomSwitch switchWithLeftText:@"男" andRight:@"女"]; custom_switch.frame = CGRectMake(100, 100, 95, 27); custom_switch.tintColor = [UIColor brownColor]; [self.view addSubview:custom_switch]; }
效果图:
自定义的UICustomSwitch请参考附件。