一旦详细视图完全,时钟将冻结。
如果用ScrollView
/VStack
代替List
,传播将会流动。
struct ContentView: View {
@State private var clocks = [Date(), Date(), Date()]
var body: some View {
NavigationView {
List {
ForEach(clocks.indices) { idx in
NavigationLink(destination: Text(clocks[idx], formatter: formatter)) {
Text("Counter (idx)")
}
}
}
}
.onReceive(Timer.publish(every: 1, on: .main, in: .default).autoconnect()) {
clocks[0] = $0
clocks[1] = $0
clocks[2] = $0
}
}
var formatter: DateFormatter {
let formatter = DateFormatter()
formatter.timeStyle = .medium
return formatter
}
}
您的目的地(Text
)只是从clocks
捕获一个静态时刻(Date
),并且没有它正在更新的事实的概念。
为什么这种情况发生在List
而不是ScrollView
中有点神秘,但我要假设SwiftUI
正在做一些事情,试图确定List
行是否相同,如果它认为它不需要重新渲染它们,为了效率,ScrollView
和VStack
不这样做。
这是一个可能的解决方案,使用ObservableObject
视图模型在视图之间传递数据,并通过Published
属性保持数据更新。
class ViewModel : ObservableObject {
@Published var time = Date()
@Published var clocks = [Date(), Date(), Date()]
var cancellable : AnyCancellable?
init() {
cancellable = Timer.publish(every: 1, on: .main, in: .default)
.autoconnect()
.sink { (date) in
self.clocks[0] = date
self.clocks[1] = date
self.clocks[2] = date
print(date)
}
}
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
NavigationView {
List {
ForEach(viewModel.clocks.indices) { idx in
NavigationLink(destination: DetailView(index: idx, viewModel: viewModel)) {
Text("Counter (idx)")
}
}
}
}.navigationViewStyle(StackNavigationViewStyle())
}
}
struct DetailView : View {
var index : Int
@ObservedObject var viewModel : ViewModel
var body: some View {
Text(viewModel.clocks[index], formatter: formatter)
}
var formatter: DateFormatter {
let formatter = DateFormatter()
formatter.timeStyle = .medium
return formatter
}
}