如何获取SwiftUI TabBar未选中项的系统默认背景色?
解决方案
要将未选中项的背景色替换为系统默认背景色,只需把代码中未选中状态的Color.white替换为**Color(.systemBackground)**即可。这个颜色会自动适配系统的浅色/深色模式,完美匹配系统默认背景风格。
修改后的完整代码如下:
enum TabItem : CaseIterable { case market case interest case wallet } struct TabBar: View { @State var tappedItem: TabItem = .market let tappedBackground = Color.primaryColor.opacity(0.2) var body: some View { HStack { TabBarItem(icon: "aqi.medium") .onTapGesture { self.tappedItem = .market } .background(self.tappedItem == .market ? tappedBackground : Color(.systemBackground)) .cornerRadius(20) .animation(.linear, value: tappedItem) TabBarItem(icon:"list.bullet.rectangle.portrait") .onTapGesture { self.tappedItem = .interest } .background(self.tappedItem == .interest ? tappedBackground : Color(.systemBackground)) .cornerRadius(20) .animation(.linear, value: tappedItem) TabBarItem(icon: "wallet.pass") .onTapGesture { self.tappedItem = .wallet } .background(self.tappedItem == .wallet ? tappedBackground : Color(.systemBackground)) .cornerRadius(20) .animation(.linear, value: tappedItem) } } }
补充说明
如果你的TabBar所在的父视图已经设置了自定义背景,也可以直接将未选中状态的背景设置为Color.clear,这样未选中项会直接继承父视图的背景色,效果同样符合需求:
.background(self.tappedItem == .market ? tappedBackground : Color.clear)
内容的提问来源于stack exchange,提问作者softshipper
相关产品推荐
相关产品推荐

