我刚刚开始进行快速编程,我试图在加载视图时调用一个函数。例如,我想在显示searchResult视图时调用getValue(),以便getValue可以填充视图中我需要的数组。
class SearchResultViewModel: ObservableObject {
var searchResults:[Any] = [] // ->Creates an instance of the struct object
var aisleArry: [Int] = []
init() {
self.getValue()
}
func getValue(){
print("We have activated searchModel")
for (productId , productVal) in Global.productDict {
let aisle = productVal.aisleNo
let name = productVal.name
let aislezone = productVal.location_zone
let aislesect = productVal.location_section
let price = productVal.productPrice
if aisleArry.contains(aisle){
print("already in aisle array")
} else {
aisleArry.append(aisle)
}
}
}
}
这是使用上面模型的searchResult视图
struct SearchResultView: View {
@ObservedObject var model: SearchResultViewModel
var body: some View {
VStack {
VStack{
HStack{
ForEach(0 ..< model.aisleArry.count){aisleNum in
Text(String(self.model.aisleArry[aisleNum])).bold()
}
}
}
Spacer()
}
}
}
在尝试了许多方法之后,我最后尝试的方法是self.getValue,该方法不起作用。加载视图后,如何在视图模型中调用函数?
调用searchResultView时未调用getValue函数。显示searchResultView时如何调用getValue函数?
答案 0 :(得分:2)
调用它出现
struct SearchResultView: View {
@ObservedObject var model: SearchResultViewModel
var body: some View {
VStack {
VStack{
HStack{
ForEach(0 ..< model.aisleArry.count){aisleNum in
Text(String(self.model.aisleArry[aisleNum])).bold()
}
}
}
Spacer()
}
.onAppear { self.model.getValue() } // << here !!
}
}
}
并使模型真正可见
class SearchResultViewModel: ObservableObject {
@Published var searchResults:[Any] = []
@Published var aisleArry: [Int] = []
func getValue(){
print("We have activated searchModel")
// ... other code
}