進入storyboard拖入Switch控件
如下圖所示點Editor中間的按鈕調出代碼
按住Ctrl鍵把控件拖到代碼裏面
鬆開設置屬性
點Connect完成
@property (weak, nonatomic) IBOutlet UISwitch *mySwitch;
使用setOn方法設置開關狀態
[self.mySwitch setOn:YES];
使用isOn方法獲得當前開關狀態
if ([self.mySwitch isOn]){
NSLog(@"The switch is on.");
} else {
NSLog(@"The switch is off.");
}
[self.mySwitch addTarget:self
action:@selector(switchIsChanged:)
forControlEvents:UIControlEventValueChanged];
實現:
- (void) switchIsChanged:(UISwitch *)paramSender{
NSLog(@"Sender is = %@", paramSender);
if ([paramSender isOn]){
NSLog(@"The switch is turned on.");
} else {
NSLog(@"The switch is turned off.");
}
}