我又回来了哈哈。我的内容视图如下所示:
struct ContentView: View {
@ObservedObject var VModel = ViewModel()
@State private var resultsNeedToBeUpdated: Bool = false
var body: some View {
VStack {
if self.resultsNeedToBeUpdated == true {
SearchResults(VModel: VModel, resultsNeedToBeUpdated: $resultsNeedToBeUpdated)
}
}
}
}
SearchBar 视图如下所示:
struct SearchResults: View {
var VModel: ViewModel
@Binding var resultsNeedToBeUpdated: Bool
var body: some View {
List {
ForEach(VModel.searchResults, id: \.self) { result in
Text(result)
}
}
}
}
最后,ViewModel 类看起来像:
class ViewModel: ObservableObject {
@Published var searchResults: [String] = []
func findResults(address: String) {
let Geocoder = Geocoder(accessToken: 'my access token')
searchResults = []
Geocoder.geocode(ForwardGeocodeOptions(query: address)) { (placemarks, attribution, error) in
guard let placemarks = placemarks
else {
return
}
for placemark in placemarks {
self.searchResults.append(placemark.formattedName)
print("Formatted name is: \(placemark.formattedName)") //this works
}
}
//I'm doing my printing on this line and it's just printing an empty array ;(
}
变量 'resultsNeedToBeUpdated' 是一个布尔绑定,当用户在搜索栏视图中键入一些文本时会更新它,它本质上只是告诉您 SearchResults 视图如果为真则应显示,如果为假则不应显示. 我要做的是根据用户输入的内容更新 SearchResults 视图。
该错误肯定与 SearchResults 视图的显示有关(我认为它仅在数组更新之前显示初始视图)。我尝试使用绑定,因为我认为它会导致 ContentView 重新加载并且它会更新 SearchResultsView 但这不起作用。