您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發實戰:UISwitch 開關控件的基本用法

編輯:iOS 開發綜合

UISwitch(開關控件)在 iOS 中十分常見,作用類似於只有兩種狀態的按鈕:ON 與 OFF。本文用一個簡短的範例,說明如何建立開關並監聽它的狀態變化。

一、關鍵程式碼

.h 檔:

@property(nonatomic,strong) UISwitch *mySwitch;

.m 檔:

@synthesize mySwitch;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //初始化開關控件,CGRectMake(x, y, 寬, 高)
    self.mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 100, 0, 0)];
    //可選擇是否設為預設的 ON 狀態
    //[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] The switch is turned on.
2013-04-22 13:46:58.878 UISwitchViewControllerTest[540:c07] The switch is turned off.

透過 UIControlEventValueChanged 事件與 isOn 判斷,就能即時掌握開關的狀態。

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