iOS 5+ 引入 UIAppearance 協議,允許通過代理模式統一修改同類控件的外觀屬性,實現全局主題定制,代碼極簡、維護性極佳。
核心兩個方法:
+ (id)appearance:影響所有該類實例[[UINavigationBar appearance] setTintColor:myColor];+ (id)appearanceWhenContainedIn:(Class<UIAppearanceContainer>)containerClass, ...:僅影響特定容器內的實例[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], [UIPopoverController class], [UITabBar class], nil] setTintColor:myColor];⚠️ 關鍵原則:必須在所有界面初始化前(如 application:didFinishLaunchingWithOptions:)統一設置,否則可能失效。
注意:並非所有屬性均支援,僅限標記 UI_APPEARANCE_SELECTOR 的屬性。
UINavigationBar *navBar = [UINavigationBar appearance];
UIImage *bgImg = [UIImage imageNamed:@"navBg.png"];
[navBar setBackgroundImage:bgImg forBarMetrics:UIBarMetricsDefault];
// 標題文字屬性
NSDictionary *titleAttrs = @{
NSFontAttributeName: [UIFont boldSystemFontOfSize:18],
NSForegroundColorAttributeName: [UIColor whiteColor]
};
[navBar setTitleTextAttributes:titleAttrs];
UITabBar *tabBar = [UITabBar appearance];
// 背景圖
[tabBar setBackgroundImage:[UIImage imageNamed:@"tabbar_bg.png"]];
// 選中指示器(需可拉伸圖片)
UIImage *selImg = [[UIImage imageNamed:@"tabbar_slider"]
resizableImageWithCapInsets:UIEdgeInsetsMake(4, 0, 0, 0)];
[tabBar setSelectionIndicatorImage:selImg];
// 圖標/文字顏色
[tabBar setTintColor:[UIColor orangeColor]];
UISegmentedControl *seg = [UISegmentedControl appearance];
// 正常狀態背景
[seg setBackgroundImage:[UIImage imageNamed:@"Segmente.png"]
forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
// 選中狀態背景
[seg setBackgroundImage:[UIImage imageNamed:@"Segmente_a.png"]
forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
// 分割線:需針對左右段組合狀態分別設置
UIImage *divider = [UIImage imageNamed:@"Segmente_line.png"];
[seg setDividerImage:divider
forLeftSegmentState:UIControlStateNormal
rightSegmentState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
[seg setDividerImage:divider
forLeftSegmentState:UIControlStateSelected
rightSegmentState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
[seg setDividerImage:divider
forLeftSegmentState:UIControlStateNormal
rightSegmentState:UIControlStateSelected
barMetrics:UIBarMetricsDefault];
// 文字屬性
NSDictionary *normalAttrs = @{NSForegroundColorAttributeName: [UIColor blackColor]};
NSDictionary *selAttrs = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
[seg setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
[seg setTitleTextAttributes:selAttrs forState:UIControlStateSelected];
BarMetrics 說明:UIBarMetricsDefault = 直向 (44pt);UIBarMetricsLandscapePhone = 橫向 (32pt)。
結合 NSNotificationCenter 或 UIAppearance 的動態特性,可在運行時切換主題:
// 定義主題配置類
@interface ThemeManager : NSObject
+ (void)applyTheme:(ThemeType)type;
@end
// 實現中統一調用 appearance 設置
// 切換時重新應用並觸發界面刷新
UIAppearance 是輕量級主題系統的最佳基礎,配合 Asset Catalog 色彩管理,可構建完整的動態換膚方案。