首页 > 解决方案 > 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

标签: swiftxcodemvvmbindingswiftui

解决方案


将行更改FavoriteStoresView为:

FavoriteStoresView(favoriteStores: self.$homeVM.favoriteStores)

$(在成员变量之前添加一个)


推荐阅读