首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 移除導航欄半透明效果:正確設定 barStyle 與外觀代理時機

     編輯:程式設計綜合問答

問題現象

在 AppDelegate 設定 [UINavigationBar appearance] setTranslucent:NO] 導致應用崩潰。appearance 代理在視圖控制器載入前生效,若導航控制器尚未建立會觸發例外。

錯誤寫法

// AppDelegate.m - 過早設定 appearance 導致崩潰
[[UINavigationBar appearance] setBarTintColor:color];
[[UINavigationBar appearance] setTranslucent:NO];  // 崩潰點

正確解法

方案一:在首個視圖控制器的 viewDidLoad 設定(推薦)

- (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 = ...;
}

方案二:使用 UINavigationBarAppearance (iOS 13+ 標準)

- (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;
}

方案三:全域 Appearance 但延遲到 didFinishLaunching 之後

- (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+ 推薦,支援滾動/邊緣樣式分離

最佳實踐

  • 優先在各視圖控制器單獨設定,避免全域副作用。
  • iOS 13+ 專案全面改用 UINavigationBarAppearance。
  • 若需全域統一風格,在 AppDelegate didFinishLaunching 設定 appearance,但需充分測試相容性。

理解 appearance 代理生效時機與 iOS 版本 API 演進,才能穩健控制導航欄外觀。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved