在 AppDelegate 設定 [UINavigationBar appearance] setTranslucent:NO] 導致應用崩潰。appearance 代理在視圖控制器載入前生效,若導航控制器尚未建立會觸發例外。
// AppDelegate.m - 過早設定 appearance 導致崩潰
[[UINavigationBar appearance] setBarTintColor:color];
[[UINavigationBar appearance] setTranslucent:NO]; // 崩潰點
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:52/255.0 green:152/255.0 blue:219/255.0 alpha:1];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque; // 非半透明深色風格
// iOS 13+ 可用
// self.navigationController.navigationBar.standardAppearance = ...;
}
- (void)viewDidLoad {
[super viewDidLoad];
UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
appearance.configureWithOpaqueBackground();
appearance.backgroundColor = [UIColor colorWithRed:52/255.0 green:152/255.0 blue:219/255.0 alpha:1];
appearance.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
self.navigationController.navigationBar.standardAppearance = appearance;
self.navigationController.navigationBar.scrollEdgeAppearance = appearance;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 此時視圖層級尚未建立,安全設定 appearance
[[UINavigationBar appearance] setBarTintColor:...];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
// 注意:iOS 13+ 建議用 UINavigationBarAppearance
return YES;
}
| 屬性 | 效果 | 備註 |
|---|---|---|
translucent = NO | 關閉半透明模糊 | iOS 7-12 有效,13+ 棄用 |
barStyle = UIBarStyleBlackOpaque | 深色不透明風格 | 自動調整狀態列文字顏色 |
UINavigationBarAppearance.configureWithOpaqueBackground() | 現代不透明外觀 | iOS 13+ 推薦,支援滾動/邊緣樣式分離 |
UINavigationBarAppearance。AppDelegate didFinishLaunching 設定 appearance,但需充分測試相容性。理解 appearance 代理生效時機與 iOS 版本 API 演進,才能穩健控制導航欄外觀。