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

SwiftUI:如何让指定TabItem选中时单独显示蓝色(其余保持白色)

实现TabView指定TabItem选中时自定义颜色

要实现仅View3的tabItem选中时变为蓝色,其余tabItem选中时保持白色,可通过绑定TabView选中状态并动态设置Label的tint颜色来实现,具体代码如下:

struct HomeScreen: View {
    @State private var selectedTab = 0
    
    var body: some View {
        TabView(selection: $selectedTab) {
            View1()
                .tabItem {
                    Label("View1", systemImage: "command")
                        .tint(selectedTab == 0 ? .white : nil)
                }
                .tag(0)
            
            View2()
                .tabItem {
                    Label("View2", systemImage: "option")
                        .tint(selectedTab == 1 ? .white : nil)
                }
                .tag(1)
            
            View3()
                .tabItem {
                    Label("View3", systemImage: "alt")
                        .tint(selectedTab == 2 ? .blue : nil)
                }
                .tag(2)
        }
        .accentColor(.white)
    }
}

// 示例子视图(可根据实际需求替换)
struct View1: View {
    var body: some View {
        Text("View 1")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.black)
            .foregroundColor(.white)
    }
}

struct View2: View {
    var body: some View {
        Text("View 2")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.gray)
            .foregroundColor(.white)
    }
}

struct View3: View {
    var body: some View {
        Text("View 3")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.blue)
            .foregroundColor(.white)
    }
}

实现说明

  1. 绑定选中状态:通过@State变量selectedTab绑定TabView的选中状态,配合.tag为每个标签分配唯一标识,用于判断当前选中项。
  2. 动态设置tint颜色:对每个tabItem内的Label使用tint修饰符,根据选中状态动态调整颜色:
    • View1、View2选中时强制设为白色,未选中时继承全局accentColor;
    • View3选中时设为蓝色,未选中时同样继承全局设置。
  3. 全局未选中颜色:.accentColor(.white)设置所有tabItem未选中时的默认颜色,若需修改未选中样式,直接替换此处颜色即可。

内容的提问来源于stack exchange,提问作者buleva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 08:34:58