Ios UICollectionView和MVVM
我试图了解如何使用MVVM开发可重用的Ios UICollectionView和MVVM,ios,swift,design-patterns,mvvm,Ios,Swift,Design Patterns,Mvvm,我试图了解如何使用MVVM开发可重用的UICollectionViewController 假设您为每种类型的UICollectionViewCell struct CollectionTestCellViewModel { let name: String let surname: String var identifier: String { return CollectionTestCell.identifier } var si
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
}
到目前为止没有问题。
但是现在考虑这个方法:<代码> uICLoopDeVIEWCopyDeaFraseDe><代码>:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let viewModel = sections[indexPath.section][indexPath.row]
return viewModel.size ?? UICollectionViewFlowLayoutAutomaticSize
}
关键是我在视图模型中有布局信息(单元的大小)。这允许我在视图控制器中放入布局委托方法,但我不知道这是否违反MVVM模式
最后一个问题是:我应该在视图模型(例如单元格)中放置什么?是否“允许”将布局数据放在视图模型内
谢谢在MVVM中,视图仅由视觉元素组成。我们只做布局、动画、初始化UI组件等事情。视图和模型之间有一个特殊的层称为ViewModel ViewModel提供了一组接口,每个接口都表示视图中的一个UI组件。我们使用一种称为“绑定”的技术将UI组件连接到ViewModel接口。因此,在MVVM中,我们不直接接触视图,而是在ViewModel中处理业务逻辑,因此视图本身也会相应地改变 我们在ViewModel而不是视图中编写表示性的东西,例如将
Date
转换为String
因此,可以在不知道视图实现的情况下为表示逻辑编写一个更简单的测试。
要了解有关iOS中MVVM的更多信息。我认为这句话有点含糊不清:“ViewModel提供了一组接口,每个接口表示视图中的一个UI组件”此表示可以包括UI内容、颜色、字体等的大小?@drakon我们在ViewModel中创建了大小、颜色等属性。然后在ViewController(我们在MVVM中的视图)中创建ViewModel的实例变量并从中获取值。@drakon如果我的答案对您有帮助,请不要忘记将其标记为答案)