在 SwiftUI 中动态更改导航标题?
Dynamically change Navigation Title in SwiftUI?
在 SwiftUI 中不能有动态导航标题吗?随着计时器的流逝,下面的代码不会更新标题。有什么办法吗? (这是在 WatchOS 中)
(为更可测试的示例编辑了代码)
import SwiftUI
struct TimerTestView: View {
@State private var timeRemaining = 100
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
Text("\(timeRemaining)")
.onReceive(timer) { time in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
}
}
.navigationTitle("\(timeRemaining)")
}
}
struct TimerTestView_Previews: PreviewProvider {
static var previews: some View {
TimerTestView()
}
}
只需打包到 NavigationView
即可解决问题 (Xcode 12.1 / watchOS 7.0)
var body: some View {
NavigationView {
Text("\(timeRemaining)")
.onReceive(timer) { time in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
}
}
.navigationTitle("\(timeRemaining)")
}
}
在 SwiftUI 中不能有动态导航标题吗?随着计时器的流逝,下面的代码不会更新标题。有什么办法吗? (这是在 WatchOS 中)
(为更可测试的示例编辑了代码)
import SwiftUI
struct TimerTestView: View {
@State private var timeRemaining = 100
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
Text("\(timeRemaining)")
.onReceive(timer) { time in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
}
}
.navigationTitle("\(timeRemaining)")
}
}
struct TimerTestView_Previews: PreviewProvider {
static var previews: some View {
TimerTestView()
}
}
只需打包到 NavigationView
即可解决问题 (Xcode 12.1 / watchOS 7.0)
var body: some View {
NavigationView {
Text("\(timeRemaining)")
.onReceive(timer) { time in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
}
}
.navigationTitle("\(timeRemaining)")
}
}