UICollectionView和MVVM

dra*_*kon 8 design-patterns mvvm ios swift

我试图了解如何使用MVVM开发可重用的UICollectionViewController.

假设您为每种类型创建视图模型 UICollectionViewCell

struct CollectionTestCellViewModel {
    let name: String
    let surname: String

    var identifier: String {
        return CollectionTestCell.identifier
    }

    var size: CGSize?
}
Run Code Online (Sandbox Code Playgroud)

细胞:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

在视图控制器中,我有类似的东西:

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
}
Run Code Online (Sandbox Code Playgroud)

到目前为止没问题.但现在考虑这种方法UICollectionViewDelegateFlowLayout:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let viewModel = sections[indexPath.section][indexPath.row]
    return viewModel.size ?? UICollectionViewFlowLayoutAutomaticSize
}
Run Code Online (Sandbox Code Playgroud)

关键是我在视图模型中有布局信息(单元格的大小).这允许我在我的视图控制器中放置布局委托方法,但我不知道这是否违反了MVVM模式.

最后一个问题是:我应该在视图模型(例如单元格)中放置什么?"允许"将布局数据放在视图模型中?

谢谢

Eug*_*rov 2

在 MVVM 中,视图仅包含视觉元素。我们只做布局、动画、初始化 UI 组件等操作。在视图和模型之间有一个特殊的层,称为 ViewModel。

\n\n

ViewModel提供了一组接口,每个接口代表View中的一个UI组件。我们使用一种名为 \xe2\x80\x9cbinding\xe2\x80\x9d 的技术将 UI 组件连接到 ViewModel 接口。所以,在 MVVM 中,我们不直接接触 View,我们在 ViewModel 中处理业务逻辑,因此 View 会相应地改变自身。

\n\n

我们编写演示性的东西,例如转换DateString我们在 ViewModel 而不是 View 中

\n\n

因此,可以在不知道视图实现的情况下为表示逻辑编写更简单的测试。

\n\n

要了解有关 iOS 中 MVVM 的更多信息,请阅读这篇文章

\n