0

一旦详细视图完全呈现,时钟将冻结。

如果你ListScrollView/替换,VStack传播将会流动。

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
    }
}
4

1 回答 1

1

您的目的地 ( Text) 只是从中捕获一个静态时刻 (a Date),clocks并且不知道它正在更新这一事实。

为什么这发生在 aList而不是ScrollViewa 有点神秘,但我会假设它SwiftUI正在做一些事情来尝试确定List行是否相同并且如果它认为不需要重新渲染它们到,为了效率,哪些ScrollViewVStack不做。

这是一个可能的解决方案,它使用视图模型在视图之间传递数据并通过属性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
        }
}
于 2021-02-06T18:45:35.417 回答