iOS7_關於UISwitch_02_如何自訂UISwitch_如何設定UISwitch的預設開關狀態_如何監聽 Switch開關狀態

來源:互聯網
上載者:User

標籤: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開關狀態

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.