UISwitch 的做用是給用戶提供開關,在系統的設置界面很常見,控件也很簡單。測試
//建立 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];
@property(nonatomic,getter=isOn) BOOL on;
on 屬性用於控制開關狀態,若是設置爲YES 則表示開啓,若是爲NO 則表示關閉,能夠經過isOn 方來判斷動畫
//1 設置開關狀態 //1.1 setOn 方法 [switch1 setOn:YES]; //1.2 setOn:animated:方法。Animated 參數是布爾類型,若值爲 YES 開關改變狀態時會顯 示動畫 [switch2 setOn:YES animated:YES] //2 判斷狀態 if ([switch1 isOn]){ NSLog(@"The switch is on."); } else { NSLog(@"The switch is off."); }
若是要在開關控件被打開或關閉時獲得通知信息,可用利用 UISwitch 的addTarget:action:forControlEvents:方法加上開關的 target。atom
// 1. 添加監聽 [switch1 addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged]; // 2.事件發生後執行的方法 /** * switchIsChanged 方法,用於監聽UISwitch控件的值改變 * * @param swith swith 控件 */ -(void)switchIsChanged:(UISwitch *)swith { if ([swith isOn]){ NSLog(@"The switch is on."); } else { NSLog(@"The switch is off."); } }
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //1.建立 UISwitch *switch1 = [[UISwitch alloc]init]; CGSize viewSize = self.view.bounds.size; switch1.frame = CGRectMake(viewSize.height*0.2, 150, 0, 0); //1.1使用 initWithFrame 方法初始化開關控件。 CGRect rect = CGRectMake(viewSize.height*0.2, 250, 0, 0); UISwitch *switch2 = [[UISwitch alloc]initWithFrame:rect]; //2 設置默認選中 //@property(nonatomic,getter=isOn) BOOL on; [switch1 setOn:YES]; //2.1 setOn:animated:方法。Animated 參數是布爾類型,若值爲 YES 開關改變狀態時會顯 示動畫 [switch2 setOn:YES animated:YES]; //3.判斷是否選中 if ([switch1 isOn]){ NSLog(@"The switch is on."); } else { NSLog(@"The switch is off."); } //4若但願在開關控件被打開或關閉時獲得通知信息,就必須在你的類中,利用 UISwitch 的addTarget:action:forControlEvents:方法加上開關的 target。以下代碼: [switch1 addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged]; //添加到UIView [self.view addSubview:switch1]; [self.view addSubview:switch2]; } /** * switchIsChanged 方法,用於監聽UISwitch控件的值改變 * * @param swith swith 控件 */ -(void)switchIsChanged:(UISwitch *)swith { if ([swith isOn]){ NSLog(@"The switch is on."); } else { NSLog(@"The switch is off."); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
2015-04-07 00:00:59.435 2UISwitch[1220:29996] The switch is on. 2015-04-07 00:01:06.134 2UISwitch[1220:29996] The switch is off. 2015-04-07 00:01:08.424 2UISwitch[1220:29996] The switch is on. 2015-04-07 00:11:57.685 2UISwitch[1220:29996] The switch is off. 2015-04-07 00:12:03.681 2UISwitch[1220:29996] The switch is on. 2015-04-07 00:12:04.219 2UISwitch[1220:29996] The switch is off. 2015-04-07 00:12:04.965 2UISwitch[1220:29996] The switch is on.