1.前言
开关空间在IOS中也十分常见,今天来介绍一下其简单用法。
2 UISwitch简介
开关空间,类似于HTML的单选按钮,只有两个状态,ON/OFF,下面上关键代码:
.h文件:
@property(nonatomic,strong) UISwitch *mySwitch;
.m文件:
@synthesize mySwitch;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
//初始化开关控件,CGRectMake(x坐标,y坐标,宽,高)
self.mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 100, 0, 0)];
//设置开关为YES状态
//[self.mySwitch setOn:YES];
//为控件添加事件
[self.mySwitch addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
//向视图中添加该控件
[self.view addSubview:self.mySwitch];
}
-(void)switchIsChanged:(UISwitch *)paramSender{
NSLog(@"Sender is=%@",paramSender);
if([paramSender isOn]){//如果开关状态为ON
NSLog(@"The switch is turned on.");
}else{
NSLog(@"The switch is turned off.");
}
}
运行结果如下:
如果选ON/OFF的时候,控制台显示:
2013-04-22 13:46:51.430 UISwitchViewControllerTest[540:c07] Sender is=<UISwitch: 0x752d530; frame = (100 100; 79 27); layer = <CALayer: 0x752e430>>
2013-04-22 13:46:51.431 UISwitchViewControllerTest[540:c07] The switch is turned on.
2013-04-22 13:46:58.877 UISwitchViewControllerTest[540:c07] Sender is=<UISwitch: 0x752d530; frame = (100 100; 79 27); layer = <CALayer: 0x752e430>>
2013-04-22 13:46:58.878 UISwitchViewControllerTest[540:c07] The switch is turned off.
3.结语
简单的例子,希望对大家有所帮助。