我很简单viewModel
:
final class EmployeeListViewModel: ObservableObject {
@Published var list = [Employee]()
init() {
// some request
self.list = [Employee, Employee]
}
}
并有一个view
:
struct EmployeeView: View {
@ObservedObject var viewModel = EmployeeListViewModel()
@State private var showContents: [Bool] = Array(repeating: false, count: viewModel.list.count)// <- error throws here
var body: some View {
GeometryReader { fullView in
ScrollView {
VStack(spacing: 40) {
ForEach(self.viewModel.list) { employee in
Text(employee.firstName).foregroundColor(.black)
}
}
}
}
}
}
错误文字:
无法在属性初始化程序中使用实例成员“ viewModel”;属性初始化程序在“自我”可用之前运行
我尝试用更改它init
:
struct EmployeeView: View {
@ObservedObject var viewModel = EmployeeListViewModel()
@State private var showContents: [Bool]
init() {
_showContents = State(initialValue: Array(repeating: false, count: viewModel.list.count)) // <- error
}
var body: some View {
GeometryReader { fullView in
ScrollView {
VStack(spacing: 40) {
ForEach(self.viewModel.list) { employee in
Text(employee.firstName).foregroundColor(.black)
}
}
}
}
}
}
但这也会引发错误:
在初始化所有存储的属性之前使用“自我”
这将引发对我叫viewModel
上init()
怎么解决呢?@State我用于卡片视图。在那里我简化了视图,以便于理解。
这是可能的解决方案
struct EmployeeView: View {
@ObservedObject var viewModel: EmployeeListViewModel // << declare
@State private var showContents: [Bool] // << declare
init() {
let vm = EmployeeListViewModel() // create here !!
// initialize both below
self.viewModel = vm
self._showContents = State(initialValue: Array(repeating: false,
count: vm.list.count))
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句