ios 如何更新swiftUI中的循环?

0qx6xfy6  于 2023-03-09  发布在  iOS
关注(0)|答案(1)|浏览(151)

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

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

            ForEach(0..<(dateTimeSelectionModel.data.count)) { index in
                VStack {
                    Text("Hello \(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, execute: {
            self.data.append(12)
            self.data.append(13)
            self.data.append(14)
        })
    }
    
    
    
}
mutmk8jj

mutmk8jj1#

使用StateObjectenumerated()尝试此方法:

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

struct DateTimeSelectionView: View {
    
    @StateObject var dateTimeSelectionModel = DateTimeSelectionViewModel() // <-- here
    
    var body: some View {
        VStack {
            Button {
                dateTimeSelectionModel.updateRecord() // <-- here, just this
            } label: {
                Text("Update Record")
            }
            ForEach(Array(dateTimeSelectionModel.data.enumerated()), id: \.offset) { item, index in   // <-- here
                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   // <-- here
    VStack {
        Text("Hello \(index)")
    }
}

注意,不建议使用此选项:

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

请注意这与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)")
            }
        }

相关问题