標籤:style blog http color os io strong 檔案 for
前言
上一篇博文,我們介紹了一下如何? UISwitch ,我們這次介紹下如何自訂 UISwitch。
原文串連:http://www.cnblogs.com/LeoYoung/p/qq907596253.html
本文
1、我們先在介面上實現一個 UISwitch。
a>在 控制器.m 檔案中,添加一個UISwitch的屬性。
1 @interface moboViewController ()
2 @property (nonatomic, strong) UISwitch *mainSwtich;
3 @end
b>在 - (void)viewDidAppear 方法中執行個體化一個 UISwitch 並添加到介面上。
1 - (void)viewDidAppear:(BOOL)animated 2 { 3 [super viewDidLoad]; 4 5 self.mainSwtich = [[UISwitch alloc]initWithFrame:CGRectMake(100, 100, 0, 0)];//執行個體化,座標為 x100,y100 6 7 [self.view addSubview:self.mainSwtich]; //添加到介面 8 }
2、自訂開關顏色:
我們首先按住 cmd,進入UISwitch標頭檔。看到三個屬性:
UIColor *onTintColor // 開啟時顏色
UIColor *tintColor // 關閉時顏色
UIColor *thumbTintColor // 開關按鈕顏色
下面我們來自訂一下,在- (void)viewDidAppear中添加如下代碼:
1 self.mainSwtich.thumbTintColor = [UIColor colorWithRed:(151./255.0) green:(81./255.0) blue:(229./255.0) alpha:1];2 3 self.mainSwtich.tintColor = [UIColor colorWithRed:(51./255.0) green:(181./255.0) blue:(229./255.0) alpha:1];4 5 self.mainSwtich.onTintColor = [UIColor colorWithRed:(51./255.0) green:(181./255.0) blue:(229./255.0) alpha:1];
註:我們用到了UIColor 類的 colorWithRed:green:blue: 方法,這個方法的色值是浮點型,所以必須用"色值./255.0",色值最好後面帶一個 . ,顯得專業一點~~~
另外色值轉換神馬的,有一個網站支援線上轉換:http://www.atool.org/colorpicker.php
3、我們來設定UISwitch的預設開關狀態:
這個很簡單,在 - (void)viewDidAppear方法中添加如下代碼:
1 [self.mainSwtich setOn:YES animated:YES];
4、監聽 UISwitch 的開關狀態:
1 [self.mainSwtich addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
再在- (void) viewDidAppear 下面,實現一下 switchIsChanged 方法:
1 - (void)switchIsChanged:(UISwitch *)paramSender2 {3 if ([self.mainSwtich isOn]) {4 NSLog(@"Switch is on");5 }6 else{7 NSLog(@"Switch is off");8 }9 }
CMD+R跑一下,點一點 開關,觀察控制台就可以看得到控制台的列印結果了!
iOS7_關於UISwitch_02_如何自訂UISwitch_如何設定UISwitch的預設開關狀態_如何監聽 Switch開關狀態