你好,歡迎來到IOS教程網

 Ios教程網 >> IOS訊息 >> 關於IOS >> IOS開發之UISwitch開關控件

IOS開發之UISwitch開關控件

編輯:關於IOS

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

2 UISwitch簡介
開關空間,類似於HTML的單選按鈕,只有兩個狀態,ON/OFF,下面上關鍵代碼:
.h文件:

@property(nonatomic,strong) UISwitch *mySwitch; 

@property(nonatomic,strong) UISwitch *mySwitch;.m文件:
 @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.");
    }
}

運行結果如下:

IOS開發之UISwitch開關控件

如果選ON/OFF的時候,控制台顯示:
 

2015-07-26 13:46:51.430 UISwitchViewControllerTest[540:c07] Sender is=<UISwitch: 0x752d530; frame = (100 100; 79 27); layer = <CALayer: 0x752e430>>

2015-07-26 13:46:51.431 UISwitchViewControllerTest[540:c07] The switch is turned on.

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

2015-07-26 13:46:58.878 UISwitchViewControllerTest[540:c07] The switch is turned off.


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