自定義 UITabBar 背景圖後,頂部仍殘留一條細線(陰影/分隔線),影響視覺一體性。設置 backgroundImage 無法覆蓋該線條。
// AppDelegate.m / didFinishLaunchingWithOptions 中
[[UITabBar appearance] setShadowImage:[UIImage imageNamed:@"transparent_1x1.png"]];
// 或 Swift
UITabBar.appearance().shadowImage = UIImage(named: "transparent_1x1")
transparent_1x1.png 放入 Assets.xcassets可用 macOS 預覽/PS/線上工具生成,或代碼動態創建:
// 動態生成 1x1 透明 UIImage (無需圖片資源)
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0);
UIColor.clear.setFill()
UIRectFill(CGRect(x: 0, y: 0, width: 1, height: 1))
let transparentImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UITabBar.appearance().shadowImage = transparentImage
backgroundImage:覆蓋整個 TabBar 背景區域shadowImage:專門控制 **頂部分隔線**(iOS 6+ 引入)shadowImage 非 nil 時,系統繪製該圖片代替預設陰影;設置為透明圖片即「隱形」appearance() 代理:全局生效,無需對每個 TabBar 實例單獨設置// SceneDelegate.swift / scene(_:willConnectTo:options:)
func configureTabBarAppearance() {
let appearance = UITabBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundImage = UIImage(named: "tabbar_bg") // 自定義背景
appearance.shadowImage = UIImage() // 空 UIImage 即透明,iOS 13+ 支援
appearance.shadowColor = .clear // 額外保障
UITabBar.appearance().standardAppearance = appearance
if #available(iOS 15.0, *) {
UITabBar.appearance().scrollEdgeAppearance = appearance
}
}
注意:iOS 13+ 推薦使用 UITabBarAppearance,shadowImage 可直接設 UIImage() (空圖片) 或 shadowColor = .clear。
| 錯誤嘗試 | 結果 | 原因 |
|---|---|---|
| tabBar.layer.borderWidth = 0 | 無效 | 陰影非 CALayer border |
| tabBar.clipsToBounds = true | 無效 | 陰影繪製在 bounds 內上方 |
| 自定義 TabBar 子類重寫 drawRect | 過度設計 | 系統提供 appearance API 即可 |
// App.swift
init() {
let appearance = UITabBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = .systemBackground // 或自定義圖片
appearance.shadowColor = .clear // 關鍵
UITabBar.appearance().standardAppearance = appearance
UITabBar.appearance().scrollEdgeAppearance = appearance
}
移除 UITabBar 頂部陰影線的標準做法是 **設置 shadowImage 為透明圖片**(iOS 12 及以下)或 **shadowColor = .clear**(iOS 13+ UITabBarAppearance)。配合 appearance() 代理一次配置全局生效,無需子類化、無副作用。切記製作 1x1 透明 PNG 或用代碼動態生成,避免引入多餘圖片資源。