小编Hol*_*ene的帖子

为什么 ForEach 在 SwiftUI 中初始化其子视图的次数是两倍?

我遇到了 SwiftUI 的ForEach视图的奇怪行为。

我注意到 ForEach 总是根据其重复次数将其子视图初始化为应有的两倍。通常,当渲染视图时,它的 init 会被调用一次。但是,如果将视图放入 ForEach 中并循环 4 次,则子视图将被初始化 8 次,而不是 4 次。

这是我想要的行为还是我错过了什么?

您可以使用下面的简单代码对其进行测试。

测试环境:Xcode 14.0.1、iOS 16、模拟器 iPhone 13 Pro(带 iOS 16)

我很感激任何反馈!

struct ContentView: View {
    
    var body: some View {
        VStack {
            // Note that ForEach is looped 4 times!
            ForEach(0..<4, id: \.self) { _ in
                CustomView() // -> this view is initialized 8 times instead of 4.
            }
        }
    }
}

struct CustomView: View {

    // custom initializer with print …
Run Code Online (Sandbox Code Playgroud)

initialization swiftui swiftui-foreach swiftui-view

11
推荐指数
0
解决办法
615
查看次数

为什么当视图消失时任务不会自动取消?

根据 Apple 文档,当视图消失时,任务将自动取消。{}

在视图消失、操作完成之前的某个时刻,SwiftUI 会自动取消任务。

为什么在这种情况下,当 ChildView 消失时,“loadData”方法中的任务没有取消?(当导航回“ParentView”时)

struct ChildView: View {
    
    @State private var data: [Double] = []
    
    private func loadData() async {
        // Why isn't this Task automatically cancelled when the ChildView disappears?
        // The Task is still executing in the background.
        Task(priority: .background) {
            // Simulating heavy data processing.
            self.data = (1...3_000_000).map { _ in Double.random(in: -10...30) }
            print("Task ended")
        }
    }
    
    var body: some View {
        Text("This is a child view")
            .task { await loadData() } …
Run Code Online (Sandbox Code Playgroud)

task async-await swift swiftui

3
推荐指数
1
解决办法
702
查看次数