標籤: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工程