1.UISwitch 創(chuàng)建
//創(chuàng)建
UISwitch *switch1 = [[UISwitch alloc]init];
CGSize viewSize = self.view.bounds.size;
switch1.frame = CGRectMake(viewSize.height*0.2, 150, 0, 0);
//使用 initWithFrame 方法初始化開關控件谱秽。
CGRect rect = CGRectMake(viewSize.height*0.2, 250, 0, 0);
UISwitch *switch2 = [[UISwitch alloc]initWithFrame:rect];
2.設置選中狀態(tài)
@property(nonatomic,getter=isOn) BOOL on;
on 屬性用于控制開關狀態(tài),如果設置為YES 則表示開啟疟赊,如果為NO 則表示關閉,可以通過isOn 方來判斷
//1 設置開關狀態(tài)
//1.1 setOn 方法
[switch1 setOn:YES];
//1.2 setOn:animated:方法近哟。Animated 參數(shù)是布爾類型,若值為 YES 開關改變狀態(tài)時會顯 示動畫
[switch2 setOn:YES animated:YES]
//2 判斷狀態(tài)
if ([switch1 isOn]){
NSLog(@"The switch is on.");
} else {
NSLog(@"The switch is off.");
}
3.添加監(jiān)聽事件
如果要在開關控件被打開或關閉時得到通知信息,可用利用 UISwitch 的addTarget:action:forControlEvents:方法加上開關的 target。
// 1. 添加監(jiān)聽
[switch1 addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
// 2.事件發(fā)生后執(zhí)行的方法
/**
*? switchIsChanged 方法吉执,用于監(jiān)聽UISwitch控件的值改變
*
*? @param swith swith 控件
*/
-(void)switchIsChanged:(UISwitch *)swith
{
if ([swith isOn]){
NSLog(@"The switch is on.");
} else {
NSLog(@"The switch is off.");
}
}