0

MVVM在 SwiftUI 的代码中有这段代码。我的目标是当应用程序第一次加载时返回没有过滤器的结果。当我按下视图上的按钮以触发CatLotViewModel重新加载过滤后的数据但似乎无法确定我可以触发它时。

class CatLotViewModel: ObservableObject {
    //MARK: - Properties
    @Published var catViewModel = [CatViewModel]()

    private var cancellabels = Set<AnyCancellable>()

    init() {
        MyAPIManager().$cat.map{ kitten in
            // Filter
            let filtered = kitten.filter{ ($0.meals.contains(where: {$0.feed == false}))}
            return filtered.map { park in
                MyCatViewModel(parking: park)
            }
//            return kitten.map { park in
//                CatViewModel(parking: park)
//            }
        }
        .assign(to: \.catViewModel, on: self)
        .store(in: &cancellabels)
    }
}
4

1 回答 1

0

使用 isFiltered 作为参数向视图模型添加加载函数。按下按钮时调用该函数。

struct ContentView: View {

    @ObservedObject var catLotViewModel = CatLotViewModel()

    var body: some View {
        Button(action: { self.catLotViewModel.load(isFiltered: true) }) {
            Text("Reload")
        }
    }
}

class CatLotViewModel: ObservableObject {
    //MARK: - Properties
    @Published var catViewModel = [CatViewModel]()

    private var cancellabels = Set<AnyCancellable>()

    init() {
        loadData(isFiltered: false)
    }

    func loadData(isFiltered: Bool) {
        MyAPIManager().$cat.map{ kitten in    
            if isFiltered {
                let filtered = kitten.filter{ ($0.meals.contains(where: {$0.feed == false}))}
                return filtered.map { park in
                    MyCatViewModel(parking: park)
                }
            } else {
                return kitten.map { park in
                    CatViewModel(parking: park)
                }
        }
        .assign(to: \.catViewModel, on: self)
        .store(in: &cancellabels)

    }
}
于 2020-06-10T13:13:15.633 回答