你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS開發(2)之UISwitch開關控件

IOS開發(2)之UISwitch開關控件

編輯:IOS開發綜合

1.前言
開關空間在IOS中也十分常見,今天來介紹一下其簡單用法。

2 UISwitch簡介
開關空間,類似於HTML的單選按鈕,只有兩個狀態,ON/OFF,下面上關鍵代碼:
.h文件:
[plain]
@property(nonatomic,strong) UISwitch *mySwitch; 

@property(nonatomic,strong) UISwitch *mySwitch;.m文件:
[plain] view plaincopyprint?@synthesize mySwitch; 
 
- (void)viewDidLoad 

    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    self.view.backgroundColor = [UIColor whiteColor]; 
    //初始化開關控件,CGRectMake(x坐標,y坐標,寬,高) 
    self.mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 100, 0, 0)]; 
    //設置開關為YES狀態 
    //[self.mySwitch setOn:YES]; 
    //為控件添加事件 
    [self.mySwitch addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged]; 
    //向視圖中添加該控件 
    [self.view addSubview:self.mySwitch]; 

 
-(void)switchIsChanged:(UISwitch *)paramSender{ 
    NSLog(@"Sender is=%@",paramSender); 
    if([paramSender isOn]){//如果開關狀態為ON 
        NSLog(@"The switch is turned on."); 
    }else{ 
        NSLog(@"The switch is turned off."); 
    } 

@synthesize mySwitch;

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    //初始化開關控件,CGRectMake(x坐標,y坐標,寬,高)
    self.mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 100, 0, 0)];
    //設置開關為YES狀態
    //[self.mySwitch setOn:YES];
    //為控件添加事件
    [self.mySwitch addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
    //向視圖中添加該控件
    [self.view addSubview:self.mySwitch];
}

-(void)switchIsChanged:(UISwitch *)paramSender{
    NSLog(@"Sender is=%@",paramSender);
    if([paramSender isOn]){//如果開關狀態為ON
        NSLog(@"The switch is turned on.");
    }else{
        NSLog(@"The switch is turned off.");
    }
}
運行結果如下:

\

如果選ON/OFF的時候,控制台顯示:
2013-04-22 13:46:51.430 UISwitchViewControllerTest[540:c07] Sender is=<UISwitch: 0x752d530; frame = (100 100; 79 27); layer = <CALayer: 0x752e430>>

2013-04-22 13:46:51.431 UISwitchViewControllerTest[540:c07] The switch is turned on.

2013-04-22 13:46:58.877 UISwitchViewControllerTest[540:c07] Sender is=<UISwitch: 0x752d530; frame = (100 100; 79 27); layer = <CALayer: 0x752e430>>

2013-04-22 13:46:58.878 UISwitchViewControllerTest[540:c07] The switch is turned off.

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved