You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:00:49