IOS學習之UISwitch控件兩種使用方法和監聽


分類: IOS開發入門 2012-06-15 11:48  1363人閱讀  評論(0)  收藏  舉報

一、第一種創建UISwitch控件的方法,在代碼中動態創建。

1、打開Xcode  4.3.2, 新建項目Switch,選擇Single View Application。

2、打開ViewController.m文件在viewDidLoad方法里添加代碼:

[cpp]  view plain copy
  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(50, 100, 20, 10)];  
  5.     [switchButton setOn:YES];  
  6.     [switchButton addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];  
  7.     [self.view addSubview:switchButton];  
  8.       
  9.     // Do any additional setup after loading the view, typically from a nib.  
  10. }  

[switchButton addTarget:selfaction:@selector(switchAction:)forControlEvents:UIControlEventValueChanged];

代碼中selector中的switchAction:需要我們自己實現,就是按下時接收到的事件。

記得把switchButton加到當前view,調用[self.viewaddSubview:switchButton];

3、監聽UISwitch按下事件

實現代碼如下:

[cpp]  view plain copy
  1. -(void)switchAction:(id)sender  
  2. {  
  3.     UISwitch *switchButton = (UISwitch*)sender;  
  4.     BOOL isButtonOn = [switchButton isOn];  
  5.     if (isButtonOn) {  
  6.         showSwitchValue.text = @"是";  
  7.     }else {  
  8.         showSwitchValue.text = @"否";  
  9.     }  
  10. }  

showSwitchValue是我通過拖拽控件方法放到界面上的Label,方便顯示效果

運行,效果:




二、通過拖拽方法使用UISwitch

1、往xib文件上拖拽一個UISwitch控件。


2、按alt+command + return鍵開啟Assistant Editor模式,選中UISwitch控件,按住Control鍵,往ViewController.h拖拽


3、選Action方式


4、.m文件中實現switchAction 。剛才動態創建的時候也用到這個方法名稱,可以先注釋掉剛才的。

[cpp]  view plain copy
  1. - (IBAction)switchAction:(id)sender {  
  2.     UISwitch *switchButton = (UISwitch*)sender;  
  3.     BOOL isButtonOn = [switchButton isOn];  
  4.     if (isButtonOn) {  
  5.         showSwitchValue.text = @"是";  
  6.     }else {  
  7.         showSwitchValue.text = @"否";  
  8.     }  
  9. }  

運行就可以了。


例子代碼:https://github.com/schelling/YcDemo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM