一、第一種創建UISwitch控件的方法,在代碼中動態創建。
1、打開Xcode 4.3.2, 新建項目Switch,選擇Single View Application。
2、打開ViewController.m文件在viewDidLoad方法里添加代碼:
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(50, 100, 20, 10)];
- [switchButton setOn:YES];
- [switchButton addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
- [self.view addSubview:switchButton];
- // Do any additional setup after loading the view, typically from a nib.
- }
[switchButton addTarget:selfaction:@selector(switchAction:)forControlEvents:UIControlEventValueChanged];
代碼中selector中的switchAction:需要我們自己實現,就是按下時接收到的事件。記得把switchButton加到當前view,調用[self.viewaddSubview:switchButton];
3、監聽UISwitch按下事件
實現代碼如下:- -(void)switchAction:(id)sender
- {
- UISwitch *switchButton = (UISwitch*)sender;
- BOOL isButtonOn = [switchButton isOn];
- if (isButtonOn) {
- showSwitchValue.text = @"是";
- }else {
- showSwitchValue.text = @"否";
- }
- }
showSwitchValue是我通過拖拽控件方法放到界面上的Label,方便顯示效果
運行,效果:

二、通過拖拽方法使用UISwitch
1、往xib文件上拖拽一個UISwitch控件。
2、按alt+command + return鍵開啟Assistant Editor模式,選中UISwitch控件,按住Control鍵,往ViewController.h拖拽
3、選Action方式
4、.m文件中實現switchAction 。剛才動態創建的時候也用到這個方法名稱,可以先注釋掉剛才的。
- - (IBAction)switchAction:(id)sender {
- UISwitch *switchButton = (UISwitch*)sender;
- BOOL isButtonOn = [switchButton isOn];
- if (isButtonOn) {
- showSwitchValue.text = @"是";
- }else {
- showSwitchValue.text = @"否";
- }
- }
運行就可以了。