0

我正在重构我的代码,并希望将成员初始化程序与 ForEach(data:,content:) 一起使用。

我有一个视图模型,其中包含符合 Identifiable 的结构数组:

class ViewModel: ObservableObject {
    @Published var int = 0
    
    var cellModels: [CellModel]
    
    init() {
        self.cellModels = [CellModel(id: 0, string: "Foo"),
                           CellModel(id: 1, string: "Bar")]
    }
}

struct CellModel: Identifiable {
    var id: Int
    var string: String
}

然后我创建了一个 CellView,它有一个 CellModel 的成员初始化器,还有一个 EnvironmentalObject,它是 ViewModel 的一个实例:

struct CellView: View {
    @EnvironmentObject var environment: ViewModel
    var cellModel: CellModel
    var body: some View {
        Text(cellModel.string)
    }
}

但是,当我创建父视图时,我在 ForEach(data:, content:) 行上收到编译器错误:

struct DemoView: View {
    @StateObject var viewModel = ViewModel()
    var body: some View {
        VStack {
            ForEach(viewModel.cellModels, content: CellView.init) // Compiler error is here
// Cannot convert value of type '(EnvironmentObject<ViewModel>, CellModel) -> CellView' to expected argument type '(CellModel) -> CellView'
        }
        .environmentObject(viewModel)
    }
}

我知道这是因为 ForEach(data:,content:) 试图将 EnvironmentObject 和单个模型都传递给每个 CellView,但是有没有办法做到这一点不必使用 ForEach(data:,content:)尾随关闭?:

ForEach(viewModel.cellModels){ cellModel in
                CellView(cellModel: cellModel)
            }
4

1 回答 1

2

使用初始化without argumentLabel

struct CellView: View {
    @EnvironmentObject var environment: ViewModel

    private var cellModel: CellModel

    init(_ cellModel: CellModel) {
        self.cellModel = cellModel
    }

    var body: some View {
        Text(cellModel.string)
    }
}

struct DemoView: View {
    @StateObject var viewModel = ViewModel()
    var body: some View {
        VStack {
            ForEach(viewModel.cellModels, content: CellView.init)
        }
        .environmentObject(viewModel)
    }
}
于 2021-06-28T14:42:42.773 回答