如何在SwiftUI中更新循环?

huangapple go评论62阅读模式
英文:

How to update the loop in swiftUI?

问题

以下是您要翻译的内容:

我有一个非常简单的视图,在视图内部运行一个包含一些文本的循环。我只想在视图模型数据更改时重新加载循环中的内容。

视图

import SwiftUI
struct DateTimeSelectionView: View {
    @ObservedObject private var dateTimeSelectionModel = DateTimeSelectionViewModel()
    var body: some View {
        VStack {
            Button {
                self.dateTimeSelectionModel.updateRecord()
                dateTimeSelectionModel.objectWillChange.send()
            } label: {
                Text("更新记录")
            }

            ForEach(0..<(dateTimeSelectionModel.data.count)) { index in
                VStack {
                    Text("你好 \(index)")
                }
            }
        }
    }
}

struct DateTimeSelectionView_Previews: PreviewProvider {
    static var previews: some View {
        DateTimeSelectionView()
    }
}

视图模型:

import Foundation

class DateTimeSelectionViewModel: ObservableObject {
    @Published var data: [Int] = Array(0...10)
    
    func updateRecord() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.data.append(12)
            self.data.append(13)
            self.data.append(14)
        }
    }
}
英文:

I have a very simple View and within the view I am running a loop having some text. I just want to reload the content within the loop whenever the viewmodel data is changing.

view

import SwiftUI
struct DateTimeSelectionView: View {
    @ObservedObject private var dateTimeSelectionModel = DateTimeSelectionViewModel()
    var body: some View {
        VStack {
            Button {
                self.dateTimeSelectionModel.updateRecord()
                dateTimeSelectionModel.objectWillChange.send()
            } label: {
                Text(&quot;Update Record&quot;)
            }
            

            ForEach(0..&lt;(dateTimeSelectionModel.data.count)) { index in
                VStack {
                    Text(&quot;Hello \(index)&quot;)
                }
                
            }
        }
        
    }
}

struct DateTimeSelectionView_Previews: PreviewProvider {
    static var previews: some View {
        DateTimeSelectionView()
    }
}

ViewModel:

import Foundation

class DateTimeSelectionViewModel: ObservableObject {
    @Published var data:[Int] = Array(0...10)
    
    func updateRecord() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
            self.data.append(12)
            self.data.append(13)
            self.data.append(14)
        })
    }
    
    
    
}

答案1

得分: 0

尝试使用StateObjectenumerated()来实现这种方法:

struct ContentView: View {
    var body: some View {
        DateTimeSelectionView()
    }
}

struct DateTimeSelectionView: View {
    
    @StateObject var dateTimeSelectionModel = DateTimeSelectionViewModel() // &lt;-- 这里
    
    var body: some View {
        VStack {
            Button {
                dateTimeSelectionModel.updateRecord() // &lt;-- 这里,只有这部分
            } label: {
                Text("Update Record")
            }
            ForEach(Array(dateTimeSelectionModel.data.enumerated()), id: \.offset) { item, index in   // &lt;-- 这里
                VStack {
                    Text("Hello \(index)")
                }
            }
        }
    }
}

class DateTimeSelectionViewModel: ObservableObject {
    @Published var data:[Int] = Array(0...10)
    
    func updateRecord() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
            self.data.append(12)
            self.data.append(13)
            self.data.append(14)
        })
    }
}

你也可以使用以下方法:

ForEach(dateTimeSelectionModel.data.indices, id: \.self) { index in   // &lt;-- 这里
    VStack {
        Text("Hello \(index)")
    }
}

请注意,不建议使用以下方式:

ForEach(0..<dateTimeSelectionModel.data.count, id: \.self) { index in

要注意itemindex之间的差异:

使用item,它是数组的内容:

ForEach(dateTimeSelectionModel.data, id: \.self) { item in
    VStack {
        Text("Hello \(item)")
    }
}

使用index,它是数组元素的索引:

ForEach(dateTimeSelectionModel.data.indices, id: \.self) { index in
    VStack {
        Text("Hello \(index)")
    }
}
英文:

try this approach, using StateObject and enumerated():

struct ContentView: View {
    var body: some View {
        DateTimeSelectionView()
    }
}

struct DateTimeSelectionView: View {
    
    @StateObject var dateTimeSelectionModel = DateTimeSelectionViewModel() // &lt;-- here
    
    var body: some View {
        VStack {
            Button {
                dateTimeSelectionModel.updateRecord() // &lt;-- here, just this
            } label: {
                Text(&quot;Update Record&quot;)
            }
            ForEach(Array(dateTimeSelectionModel.data.enumerated()), id: \.offset) { item, index in   // &lt;-- here
                VStack {
                    Text(&quot;Hello \(index)&quot;)
                }
            }
        }
    }
}

class DateTimeSelectionViewModel: ObservableObject {
    @Published var data:[Int] = Array(0...10)
    
    func updateRecord() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
            self.data.append(12)
            self.data.append(13)
            self.data.append(14)
        })
    }
}

You could also use:

ForEach(dateTimeSelectionModel.data.indices, id: \.self) { index in   // &lt;-- here
    VStack {
        Text(&quot;Hello \(index)&quot;)
    }
}

Note, it is not recommended to use this:

ForEach(0..&lt;(dateTimeSelectionModel.data.count), id: \.self) { index in

Be aware of the difference between this, with item, that is the contents of the array:

        ForEach(dateTimeSelectionModel.data, id: \.self) { item in
            VStack {
                Text(&quot;Hello \(item)&quot;)
            }
        }

and this with index, the index of the array elements:

        ForEach(dateTimeSelectionModel.data.indices, id: \.self) { index in
            VStack {
                Text(&quot;Hello \(index)&quot;)
            }
        }

huangapple
  • 本文由 发表于 2023年3月9日 13:51:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75680868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定