iOS5及其以後提供了一個比較強大的工具UIAppearance,我們通過UIAppearance設置一些UI的全局效果,這樣就可以很方便的實現UI的自定義效果又能最簡單的實現統一界面風格,它提供如下兩個方法。
+ (id)appearance
這個方法是統一全部改,比如你設置UINavBar的tintColor,你可以這樣寫:[[UINavigationBar appearance] setTintColor:myColor];
+ (id)appearanceWhenContainedIn:(Class <>)ContainerClass,...
這個方法可設置某個類的改變:例如:設置UIBarButtonItem 在UINavigationBar、UIPopoverController、UITabbar中的效果。就可以這樣寫
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], [UIPopoverController class],[UITabbar class] nil] setTintColor:myPopoverNavBarColor];
請注意*使用appearance設置UI效果最好采用全局的設置,在所有界面初始化前開始設置,否則可能失效。
支持UIAppearance協議的類可以訪問appearance selector ,它為receiver返回appearance proxy,我麼可以給proxy發一些消息,諸如setTintColor:等
但是它並不是支持所有的UI類。下面列出它支持的類
1.UIActivitiIndicatorView
2.UIBarButtonItem
3.UIBarItem
4.UINavgationBar
5.UIPopoverControll
6.UIProgressView
7.UISearchBar
8.UISegmentControll
9.UISlider
10.UISwitch
11.UITabBar
12.UITabBarItem
13.UIToolBar
14.UIView
15.UIViewController
具體UI外觀修改如下:
1.修改導航欄背景
代碼如下:
UINavigationBar * appearance = [UINavigationBar appearance];
UIImage *navBackgroundImg =[UIImage imageNamed:@"navBg.png”];
[appearance setBackgroundImage:navBackgroundImgforBarMetrics:UIBarMetricsDefault];
2.標簽欄(UITabbar)
代碼如下:
UITabBar *appearance = [UITabBar appearance];
//設置背景圖片
[appearance setBackgroundImage:[UIImage imageNamed:@"tabbar_bg.png"]];
//門置選擇item的背景圖片
UIImage * selectionIndicatorImage =[[UIImageimageNamed:@"tabbar_slider"]resizableImageWithCapInsets:UIEdgeInsetsMake(4, 0, 0,0)] ;
[appearance setSelectionIndicatorImage:selectionIndicatorImage];
3.分段控件(UISegmentControl)
代碼如下:
UISegmentedControl *appearance = [UISegmentedControl appearance];
//Segmenteg正常背景
[appearance setBackgroundImage:[UIImage imageNamed:@"Segmente.png"]
forState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
//Segmente選中背景
[appearance setBackgroundImage:[UIImage imageNamed:@"Segmente_a.png"]
forState:UIControlStateSelected
barMetrics:UIBarMetricsDefault];
//Segmente左右都未選中時的分割線
//BarMetrics表示navigation bar的狀態,UIBarMetricsDefault 表示portrait狀態(44pixel height),UIBarMetricsLandscapePhone 表示landscape狀態(32pixel height)
[appearance setDividerImage:[UIImage imageNamed:@"Segmente_line.png"]
forLeftSegmentState:UIControlStateNormal
rightSegmentState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
[appearance setDividerImage:[UIImage imageNamed:@"Segmente_line.png"]
forLeftSegmentState:UIControlStateSelected
rightSegmentState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
[appearance setDividerImage:[UIImage imageNamed:@"Segmente_line.png"]
forLeftSegmentState:UIControlStateNormal
rightSegmentState:UIControlStateSelected