Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/111.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios UICollectionView和MVVM_Ios_Swift_Design Patterns_Mvvm - Fatal编程技术网

Ios UICollectionView和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

我试图了解如何使用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
}
到目前为止没有问题。 但是现在考虑这个方法:<代码> 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如果我的答案对您有帮助,请不要忘记将其标记为答案)