我刚刚学会了快速编程,我试图在加载 View 时调用一个函数。例如,我想在显示 searchResult View 时调用 getValue() ,以便 getValue 可以填充 View 中我需要的数组。
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 View
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 ,它不起作用。加载 View 时如何调用 View 模型中的函数?
调用 searchResultView 时,未调用 getValue 函数。当searchResultView显示时如何调用getValue函数?
最佳答案
出现时调用
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
}
关于swift:如何调用 Observableobject 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63304285/