在这种情况下,我能理解的是:
您应该创建3
ViewModels
-
视图模型
对于
ViewController
-
自定义表视图单元格视图模型
对于
CustomTableViewCellView
-
自定义集合视图单元格视图模型
对于
CustomCollectionViewCellView
以下是您的
视图模型
应该看起来像,
class ViewModel
{
private var cellVMs = [CustomTableViewCellViewModel] = []
var reloadTableViewClosure: (()->())?
var numberOfLibraries: Int {
return self.cellVMs.count
}
func getLibraryCellVM(at indexPath: IndexPath) -> CustomTableViewCellViewModel
{
return self.cellVMs[indexPath.row]
}
//MARK: Initializer
init()
{
self.fetchLibraryList()
}
//MARK: Private Methods
private func fetchLibraryList()
{
if let path = Bundle.main.path(forResource: "LibraryList", ofType: "json")
{
if let libraryList = try? JSONDecoder().decode([Library].self, from: Data(contentsOf: URL(fileURLWithPath: path)))
{
libraryList.forEach({
cellVMs.append(CustomTableViewCellViewModel(library: $0))
})
self.reloadTableViewClosure?()
}
}
}
}
你的
CustomTableViewCellViewModel
看起来像这样,
class CustomTableViewCellViewModel {
var booksVMs: [CustomCollectionViewCellViewModel] = []
var library: Library!
init(library: Library) {
self.library = library
// Initialize booksVMs
library.books.forEach({
booksVMs.append(CustomCollectionViewCellViewModel.init(book: $0))
})
}
var numberOfBooks: Int {
self.booksVMs.count
}
func bookViewModel(at indexPath: IndexPath) -> CustomCollectionViewCellViewModel {
return self.booksVMs[indexPath.row]
}
}
最后
CustomCollectionViewCellViewModel
看起来像这样,
class CustomCollectionViewCellViewModel {
var book: Book!
init(book: Book) {
self.book = book
}
var bookName: String? {
return self.book.name
}
}