開關控制項 UISwitch
ViewController.h:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController{ //宣告一個開關控制項 //作用是在兩種狀態間切換 //開 / 關 //注意:UIKit 框架裡的類都以 UI 開頭 //蘋果官方的控制項都定義在 UIKit 框架中 UISwitch * _mySwitch; } @property(retain,nonatomic) UISwitch * mySwitch; @end
ViewController.m:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize mySwitch=_mySwitch; - (void)viewDidLoad { [super viewDidLoad]; //建立開關物件 //它同樣繼承自 UIView _mySwitch = [[UISwitch alloc]init]; //官方控制項的位置設定 //X、Y 可以改 //寬高改不了(寫了也不生效,系統固定) _mySwitch.frame=CGRectMake(100, 200, 180, 40); //設定開關狀態 //YES:開啟 //NO:關閉 _mySwitch.on=YES; //也可以用 setter //[_mySwitch setOn:YES]; //設定狀態並帶動畫 //參數一:狀態 //參數二:是否播放動畫 //[_mySwitch setOn:YES animated:YES]; [self.view addSubview:_mySwitch]; //設定開啟狀態的底色 [_mySwitch setOnTintColor:[UIColor orangeColor]]; //設定滑塊(圓按鈕)的顏色 [_mySwitch setThumbTintColor:[UIColor blueColor]]; //設定整體外觀顏色,滑塊的白色其實是父層背景的顏色 [_mySwitch setTintColor:[UIColor greenColor]]; //為開關註冊事件 //參數一:事件處理的目標物件 //參數二:事件處理的方法 //參數三:觸發事件的類型,UIControlEventValueChanged 代表狀態改變時觸發 [_mySwitch addTarget:self action:@selector(swChange:) forControlEvents:UIControlEventValueChanged]; } //參數直接帶入開關物件本身 - (void) swChange:(UISwitch*) sw{ if(sw.on==YES){ NSLog(@"開關被打開"); }else{ NSLog(@"開關被關閉"); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // 釋放可重建的資源 } @end
幾個實務上值得留意的點:on 屬性決定初始狀態;UIControlEventValueChanged 是唯一常用的事件類型,因為 UISwitch 只有「值改變」這一種互動語意;三個 tintColor 分別控制外框、滑塊與開啟底色,配色時要一起考慮才不會花掉。以上就是 UISwitch 的完整用法,希望對入門的朋友有幫助。