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

如何自定义选中状态的NavigationBarItem?移除指示器及修改文字颜色

1. 移除选中项的环绕指示器

SwiftUI 实现方式

方法一:自定义TabView样式完全替换系统布局

struct CustomTabStyle: TabViewStyle {
    func makeBody(configuration: Configuration) -> some View {
        HStack(spacing: 0) {
            ForEach(configuration.items) { item in
                Button {
                    configuration.select(item)
                } label: {
                    item.label
                        .padding(.vertical, 8)
                        .frame(maxWidth: .infinity)
                }
                .foregroundColor(configuration.selection == item ? .orange : .gray)
            }
        }
        .background(Color.white)
        .border(.lightGray, edge: .top)
    }
}

// 使用示例
TabView {
    Text("首页页面")
        .tabItem { Text("hello") }
    Text("设置页面")
        .tabItem { Text("settings") }
}
.tabViewStyle(CustomTabStyle())

方法二:通过UIKit外观设置隐藏指示器

在App启动入口(如App.swift)或视图初始化时添加:

UITabBar.appearance().selectionIndicatorImage = UIImage()

UIKit 实现方式

如果是导航栏按钮(UIBarButtonItem)的选中边框,直接清空背景图:

let helloBarItem = UIBarButtonItem(title: "hello", style: .plain, target: self, action: #selector(onHelloTap))
helloBarItem.setBackgroundImage(UIImage(), for: .selected, barMetrics: .default)

2. 修改选中后的文字颜色

SwiftUI 实现方式

方式一:全局设置选中色调

TabView {
    Text("首页页面")
        .tabItem { Text("hello") }
    Text("设置页面")
        .tabItem { Text("settings") }
}
.accentColor(.red) // 统一设置所有选中Tab的文字、图标颜色

方式二:自定义样式时单独控制

在上述自定义CustomTabStyle中,通过foregroundColor属性区分选中/未选中的文字颜色,直接修改对应颜色值即可。

UIKit 实现方式

为UIBarButtonItem设置不同状态的文字属性:

let helloBarItem = UIBarButtonItem(title: "hello", style: .plain, target: self, action: #selector(onHelloTap))
// 选中状态颜色
helloBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.blue], for: .selected)
// 正常状态颜色
helloBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:03:12