使用过滤器使用 MVVM 在 SwiftUI 中重新加载数据
Reload data in SwiftUI using MVVM using filters
我在 SwiftUI 的 MVVM
代码中有这段代码。我的 Objective 是应用程序首次加载时 return 没有过滤器的结果。当我按下视图上的按钮触发 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{ ([=10=].meals.contains(where: {[=10=].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)
}
}
使用 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{ ([=10=].meals.contains(where: {[=10=].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)
}
}
我在 SwiftUI 的 MVVM
代码中有这段代码。我的 Objective 是应用程序首次加载时 return 没有过滤器的结果。当我按下视图上的按钮触发 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{ ([=10=].meals.contains(where: {[=10=].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)
}
}
使用 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{ ([=10=].meals.contains(where: {[=10=].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)
}
}