简体   繁体   中英

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

Change the line with FavoriteStoresView to:

FavoriteStoresView(favoriteStores: self.$homeVM.favoriteStores)

(add a $ before the member var)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM