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

watchOS中使用带自定义颜色的Text时,如何保留导航标题滚动行为?

watchOS SwiftUI 导航标题自定义Text后自动滚动失效问题

在watchOS SwiftUI开发中遇到一个问题:

  • 使用String作为导航标题时,长标题会按预期自动滚动
  • 切换为带自定义前景色的Text作为导航标题后,自动滚动功能完全失效

观察到watchOS系统设置应用能实现蓝色导航标题+自动滚动的效果,说明技术上是可行的,求正确的实现方式。

复现代码

struct ContentView: View {
 
  var body: some View {
    NavigationStack {
      NavigationLink("Go Next") {
        LinkView()
      }
    }
  }
}
 
struct LinkView: View {
 
  enum NavigationTitleMode: String {
    case string
    case text
  }
 
  @State private var titleMode: NavigationTitleMode = .string
 
  let title: String = "Watch UI Test Navigation Title"
 
  var body: some View {
    switch titleMode {
    case .string:
      content
        .navigationTitle(title)
    case .text:
      content
        .navigationTitle {
          Text(title)
            .foregroundStyle(.blue)
        }
    }
  }
 
  var content: some View {
    VStack {
      Text("Mode: \(titleMode.rawValue)")
 
      Button("Change Mode", systemImage: "pencil") {
        titleMode = titleMode == .string ? .text : .string
      }
    }
    .padding()
    .navigationBarTitleDisplayMode(.inline)
  }
}

效果对比

  • String模式(正常滚动):
    String Mode

  • Text模式(滚动失效):
    Text Mode


解决方案

方案1:直接修改系统标题颜色(推荐)

不需要自定义Text,通过navigationBarTitleTextColor直接修改系统默认标题的颜色,这种方式完全保留系统的自动滚动逻辑:

content
  .navigationTitle(title)
  .navigationBarTitleTextColor(.blue)

这个方案和系统设置应用的实现逻辑一致,既能得到自定义颜色,又不会丢失自动滚动功能。

方案2:自定义滚动容器(复杂样式场景)

如果需要更复杂的标题样式(比如混排图标/不同字号),可以手动给Text添加滚动容器模拟系统行为,示例:

.navigationTitle {
  ScrollView(.horizontal, showsIndicators: false) {
    Text(title)
      .foregroundStyle(.blue)
      .fixedSize(horizontal: true, vertical: false)
  }
  .frame(width: 160) // 适配watchOS导航栏宽度
}

但这种方式需要自己处理滚动动画逻辑,不如方案1简洁,仅在特殊场景使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 05:12:45