ObservedObject不可转换为Binding

时间:2019-12-22 18:19:05

标签: swift xcode mvvm binding swiftui

我正在尝试通过swiftUI实现MVVM

所以我有这个视图模型

class HomeViewModel: ObservableObject {
    @Published var favoriteStores = Array<ItemStore>()

    init() {
        for i in 0...10 {
            favoriteStores.append(ItemStore(storeName: "Store \(i)", storeImg: "image url"))
        }
    }
}

此视图:

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()
                }

            }
        }
    }
}

这里的问题是当我使用self.homeVM.favoriteStores时:'[ItemStore]' is not convertible to 'Binding<[ItemStore]>'

但是当我改用@State var faves时,效果很好

我看了很多教程,它应该像这样工作,因为swiftUI处理了这部分,并用 Binding

进行了包装

1 个答案:

答案 0 :(得分:0)

将带有FavoriteStoresView的行更改为:

FavoriteStoresView(favoriteStores: self.$homeVM.favoriteStores)

(在成员var之前添加$