問題描述
iOS 13 UINavigationBar 新增了 scrollEdgeAppearance 屬性。
但是這個屬性在 IOS14 及其更早的版本中 只應用在大標題導航欄上,在 iOS15 中這個屬性適用於所有導航欄。
scrollEdgeAppearance 是 UINavigationBarAppearance 類型,里面有幾個屬性:
1. backgroundEffect:基於 backgroundColor 或 backgroundImage 的磨砂效果
2. backgroundColor:注意 這個屬性在 backgroundImage 下(在某個界面單獨設置導航欄顏色,直接使用 backgroundColor 無效,被 backgroundImage 遮住了)

如果設置導航欄透明 ,也會無效。
原因:新的導航欄 在加入 large 模式之后 apple 會對普通模式的 nav 的 _UIbarBackground 進行一次 alpha = 1 的設置。
我們直接改變其 subview 的 alpha 就好了。
解決方法:
3. backgroundImage:背景圖片
4. backgroundImageContentMode : 渲染 backgroundImage 時使用的內容模式。 默認為 UIViewContentModeScaleToFill 。
5. shadowColor:底部分割線陰影顏色
6. shadowImage: 陰影圖片
全局設置 導航欄透明問題
不透明
if #available(iOS 15.0, *) { let app = UINavigationBarAppearance() app.configureWithOpaqueBackground() // 重置背景和陰影顏色 app.titleTextAttributes = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.white ] app.backgroundColor = UIColor.init(hexString: "#2C81EC") // 設置導航欄背景色 app.shadowColor = .clear UINavigationBar.appearance().scrollEdgeAppearance = app // 帶scroll滑動的頁面 UINavigationBar.appearance().standardAppearance = app // 常規頁面。描述導航欄以標准高度 }
透明
因為 scrollEdgeAppearance = nil ,如果當前界面中使用可了 ScrollView ,當 ScrollView 向上滾動時 scrollEdgeAppearance 會默認使用 standardAppearance。因此 backgroundEffect 和 shadowColor 也要顯式設置為 nil ,防止 backgroundEffect、shadowColor 出現變成有顏色
if #available(iOS 15.0, *) { let app = UINavigationBarAppearance() app.configureWithOpaqueBackground() // 重置背景和陰影顏色 app.backgroundEffect = nil app.titleTextAttributes = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.white ] app.backgroundColor = .clear // 設置導航欄背景色 app.shadowColor = nil UINavigationBar.appearance().scrollEdgeAppearance = nil // 帶scroll滑動的頁面 UINavigationBar.appearance().standardAppearance = app // 常規頁面。描述導航欄以標准高度 }