iOS實用技巧 - 簡易實現多皮膚功能

來源:互聯網
上載者:User

標籤:style   http   color   使用   os   io   

前言:不記得誰說的了,中國的使用者大概是世界上最喜歡多皮膚功能的使用者了。我很討厭寫安卓程式,圖形介面設計工具及其難用,還不如手寫,編輯器慢如蝸牛,智能提示總是跟不上我輸入的速度,相同的功能,安卓的代碼量至少是iOS的三倍,每寫一行代碼,都覺得自己的手指在滴血。可是安卓靈活統一的style功能確實很貼心!5之前,iOS平台上實現相同的功能一直沒有個比較好的辦法。

  iOS5之後,蘋果將所有介面組件的設定,都綁定在一個叫UIAppearance的協議上了,你可以簡單的通過UIAppearance設定組件的全域風格。

  例如,我想把所有的UIButton的title都設成白色:

 [[UIButton appearance] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

  或者,我想所有的UIButton都有統一的背景圖片

 [[UIButton appearance] setBackgroundImage:aBackgroundImage forState:UIControlStateNormal];

  這樣,整個應用的UIButton,title都是白色,背景使用aBackgroundImage的圖片了。

  當然,實際項目中,不同風格的組件,應該單獨定義成一個類,然後在它的initialize方法設定它的UIAppearance,例如我定義了一個AFKButton類,我就可以寫成下面這樣,這樣應用中所有的AFKButton類的Button都是一個風格的了。

@implementation AFKButton  ...... + (void)initialize {     if (self == [AFKButton self]) { [[self appearance] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];  [[self appearance] setBackgroundImage:aBackgroundImage forState:UIControlStateNormal];     } }......@end


  修改UIAppearance,有個限制,就是如果想讓它生效,必須在下次裝載入app的主視窗時才會生效,所以,如果要通過UIAppearance動態修改組件的風格,我們就需要在UIAppDelegate中實現下面的代碼

 UIViewController *rootViewController = self.window.rootViewController; self.window.rootViewController = nil; [[UIButton appearance] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [[UIButton appearance] setBackgroundImage:aBackgroundImage forState:UIControlStateNormal];  self.window.rootViewController = rootViewController;

  由上所述,我設計的動態切換皮膚的風格如下:

1.首先按照風格建立相應的組件類,例如,你有幾種Button,就繼承實現幾個Button類。

2.設定全域風格標誌。

3.觸發風格修改的地方,通過全域廣播發送訊息。

4.UIAppDelegate重新裝載window的rootViewController


DEMO工程


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.