簡體   English   中英

MVVM 設計模式實現

[英]MVVM Design pattern implementation

我要求實現MVVM設計模式,所以在這里我有一個HomeViewController

Which contains a HomeViewModel , HomeViewController has a tableView and some other UIKit components in MVVM i read that Every UIView should have its own ViewModel so for the cells of UITableView (HomeTableViewCell) each one should hase its own ViewModel, so should HomeViewModel contains A Collection of將傳遞給每個單元格的單元格的子視圖模型,或者它的正確實現是什么,最好的方案是什么?

extension HomeViewController : UITableViewDelegate , UITableViewDataSource{
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.articlesCount ?? 0
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    }


}

我讀到每個 UIView 都應該有自己的 ViewModel

您是對的,但請記住,要越來越深入地觀察每個UIKit組件的 MVVM 可能會變得復雜並且需要很多時間。 所以我的建議是始終考慮項目情況和截止日期。

另外,我建議你有代碼風格 閱讀它們,例如在您的代碼中注意到您的 class 名稱以小寫myCell ,這並不常見。


回答你的問題:

記住這一點:model 不應該訪問UITableViewCell

為 MyCell 添加新視圖 Model:

這是一個基本視圖 model 用於處理自定義 tableViewCell 邏輯和數據。

class MyCellViewModel {
    private let model: CellModel
    init(model: CellModel) {
        self.model = model
    }
}

// properties TableViewCell needs.
extension MyCellViewModel {
    var title: Any {
        return model.title
    }

    var someImage: Any {
        return model.image
    }
    // add variables or functions...

}

更新自定義 UITableViewCell、MyCell:

添加一個可選變量來保存 viewModel 並在查看 model didSet時更新視圖。

class myCell: UITableViewCell {
    var viewModel: MyCellViewModel? {
        didSet {
            guard let viewModel = viewModel else { return }

            // just an example
            titleLabel.text = viewModel.title
        }
    }
}

在 HomeViewController 的 View Model 中添加:

現在我們需要從控制器的視圖 model 傳遞自定義UITableViewCell的視圖 model。

func viewModelForCell(atIIndexPath: IndexPath) -> MyCellViewModel {
        return MyCellViewModel(model: articles[indexPath.row])
}

這個基本實現只是為了展示避免視圖訪問 model 並處理視圖 Model 中的所有邏輯過程的 MVVM 概念,當然您可以改進它並根據您的需要采用它,快樂編碼!

我認為您要問的是單元格的 model。 您可以為您的單元格 model 編寫簡單的結構。

struct CellModel {
   let data: Any
}

那么你的 controller model 就可以了

let controllerData = [DataForCellModels]() 

在基本情況下。

然后你繼承 TableviewCell

class myCell: UITableViewCell {
    let model: CellModel {
       didSet {
           updateCell()
       }
    }
}

然后控制您的單元格,這需要您通過 cellID 實現單元格。

我希望這可以讓您了解如何實現它,但有關更多詳細信息,我建議您搜索完整的教程。

祝你的項目好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM