2017-09-11 15 views
0

我正在为我最近的项目使用VIPER架构。 但我想知道如何实现UITableView数据源。用于VIPER中UITableView数据源的ViewModel swift

在VIPER中,视图是被动的。他们将事件发送给Presenter,然后Presenter将适当的ViewData(ViewModel)发送到View。

所以我在视图中存储ViewView的ViewModels。 (View不问数据演示。)

class View: UIViewController, UITableViewDataSource { 
    var viewModels: [CellViewModelType] = [] 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return viewModels.count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let viewModel = viewModels[indexPath.row] 
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIndetifier", for: indexPath) 
    cell.configure(with: viewModel) 
    return cell 
    } 
} 

当用户的tableView选择项目,查看与indexPath发送didSelectItemAt事件演示。然后Presenter决定事件的正确动作,推送VC或获取数据。

所以Presenter应该知道ViewData(或Real Data)。 或Presenter将事件传递给Interactor,因为Interactor存储实数据。

这是我的同步困境。数据传播查看,演示者,交互者。他们可能会有所不同,因为真实数据可以在后台异步更改(如聊天应用程序)

任何帮助将不胜感激。 :D

回答

0

我说得对,您担心Presenter或Interactor中的ViewModels数组和数据数组中的数据不一致? 如果是这样,当Interactor获取新数据时,它将传递给Presenter。在那里,我更愿意先将它作为ViewModels同步发送到View,然后将其设置为Presenter的Data数组。 当您拨打didSelectCellAtIndexPath:并发送带有IndexPath的事件给Presenter时,从Data数组访问数据中的额外检查是个不错的主意。

0

演示者应存储ViewModels和Interactor应存​​储的实体。所以查看应要求主持人对的ViewModels像这样

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let viewModel = presenter.getViewModel(at: indexPath.row) 
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIndetifier", for: indexPath) 
    cell.configure(with: viewModel) 
    return cell 
} 

当用户选择一个项目的提交者可以deside来调用交互器的方法。因此,模块状态仅存储在Interactor中,视图状态存储在Presenter中。查看不应有任何状态