我正在尝试了解如何使用MVVM来开发可重用的UICollectionViewController
。
假设你为每种UICollectionViewCell
类型创建一个视图模型。
struct CollectionTestCellViewModel {
let name: String
let surname: String
var identifier: String {
return CollectionTestCell.identifier
}
var size: CGSize?
}
细胞:
class CollectionTestCell: UICollectionViewCell {
@IBOutlet weak var surnameLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
func configure(with viewModel: CollectionTestCellViewModel) {
surnameLabel.text = viewModel.surname
nameLabel.text = viewModel.name
}
}
在视图控制器中,我有类似下面的代码:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let viewModel = sections[indexPath.section][indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: viewModel.identifier, for: indexPath)
configure(view: cell, with: viewModel)
return cell
}
到目前为止没有问题。
但现在考虑一下这个UICollectionViewDelegateFlowLayout
的方法:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let viewModel = sections[indexPath.section][indexPath.row]
return viewModel.size ?? UICollectionViewFlowLayoutAutomaticSize
}
问题是我在视图模型中有布局信息(单元格的大小)。这使我可以在我的视图控制器中放置布局委托方法,但我不知道这是否违反了MVVM模式。
最后的问题是:我应该在视图模型中放什么(例如一个单元格)?将布局数据放在视图模型中是否“允许”?
谢谢