swift - ObservedObject not convertible to Binding
问题描述
I'm trying to implement MVVM with swiftUI
So I have this view model
class HomeViewModel: ObservableObject {
@Published var favoriteStores = Array<ItemStore>()
init() {
for i in 0...10 {
favoriteStores.append(ItemStore(storeName: "Store \(i)", storeImg: "image url"))
}
}
}
And this view :
struct HomeView: View {
@ObservedObject var homeVM = HomeViewModel()
@State var faves = [
ItemStore(storeName: "Store 0", storeImg: "image url"),
ItemStore(storeName: "Store 1", storeImg: "image url"),
ItemStore(storeName: "Store 2", storeImg: "image url")
]
@State var searchText = ""
var body: some View {
NavigationView{
GeometryReader { geometry in
ScrollView{
VStack{
SearchBarView(searchText: self.$searchText)
Spacer()
.padding(.vertical, 5.0)
FavoriteStoresView(favoriteStores: self.homeVM.favoriteStores)
FiltersView()
StoresView()
}.padding()
}
}
}
}
}
the problem here is when i use self.homeVM.favoriteStores
i got : '[ItemStore]' is not convertible to 'Binding<[ItemStore]>'
but when i use @State var faves
instead , it works fine
i saw lot of tutorials , and it should work like that , because swiftUI handle this part , and it wrap it with Binding
解决方案
将行更改FavoriteStoresView
为:
FavoriteStoresView(favoriteStores: self.$homeVM.favoriteStores)
$
(在成员变量之前添加一个)
推荐阅读
- python - 在 CNN,张量流中初始化后形状怪异的内核
- haskell - 使用简单函数使用 'print' 引起的模棱两可的类型变量 'a0'
- r - R Shiny:renderUI + uiOutput多个输入条件异步
- angular - Angular CDK 虚拟滚动不会一次选择 matselect 中的所有列大型数据集
- r - dplyr 组操作添加 na
- javascript - 从 Vue 中的插槽更新父级中的状态
- javascript - 将文件从我的服务器 API 上传到另一个 API - Node JS (Express)
- c++ - 如何使用内置排序功能对二维数组进行排序
- amazon-web-services - Jenkins 管道正在抛出无法连接到端点 URL:“https://ecs.ap-south-1.amazonaws.com/”
- javascript - 未捕获的 TypeError:google.translate.TranslateService 不是构造函数