MVVM在Swift中的應(yīng)用(利用TableView實現(xiàn))

為了好看隨便放張圖XD

前言

在OC中成熟的框架已經(jīng)有很多了,但是Swift一直找不到..可能是我檢索能力不強,希望大家能推薦給我,我只在viewModel中抽象了幾個常用的方法,如果需要可以自己在里面擴展
文章里還講了一點AutoLayout計算cell高度的方法

上代碼

ViewModel

主要是把tableView的Delegate和DataSource拆分出來,利用Block讓ViewController可以生成cell,和處理點擊事件

import UIKit

typealias ZECellRenderBlock = (indexPath:NSIndexPath,tablleView:UITableView) -> UITableViewCell!
typealias ZECellSelectBlock = (indexPath:NSIndexPath,tablleView:UITableView) -> Void

class ZETableViewModel: NSObject,UITableViewDelegate,UITableViewDataSource {
    
    var cellRender:ZECellRenderBlock! // 創(chuàng)建cell的block
    var cellSlect:ZECellSelectBlock? // 選中cell的block
    var cellHeight:CGFloat = UITableViewAutomaticDimension
    var estimatedHeight:CGFloat = 50// 預(yù)估高度
    var sectionCount:Int = 0// 區(qū)數(shù)
    var rawCount:Int = 0// 行數(shù)
    
    /** 區(qū)數(shù) */
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return sectionCount
    }
    /** 行數(shù) */
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return rawCount
    }
    /** 行高 */
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return cellHeight
    }
    /** cell */
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = cellRender(indexPath: indexPath,tablleView: tableView)
        return cell
    }
    /** 預(yù)估高度 */
    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return estimatedHeight
    }
    /** 點擊事件 */
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        guard let selectBlock = cellSlect else{
            print("cell的選中block沒有實例")
            return
        }
        selectBlock(indexPath:indexPath,tablleView:tableView)
    }
}

Model

我一般喜歡把model當做controller的垃圾桶,把所有非View方法都封裝到model中,這里寫了一個模擬網(wǎng)絡(luò)請求的方法

import UIKit
typealias ModelBlock = (success:Bool,status:String) -> Void
class ZEVCModel: NSObject {
    
    var dataArr:Array<ZESomeData> = []

    func getData(block:ModelBlock){
        for dic in self.someData{
            
            let title = dic["bigTitle"]
            let context = dic["context"]
            let model = ZESomeData(bigTitle:title, context: context)
            dataArr.append(model)
        }
        block(success: true, status: "獲取數(shù)據(jù)成功")
    }
    
    var someData = [
        [
            "bigTitle":"我是大標題",
            "context":"我是一個超長超長超長超長超長超長超長超長超長超長超長超長超長超長的內(nèi)容"
        ]
    ]
}

View

這里僅用一個Cell來表示View,可以講一下通過AutoLayout自動計算cell高度的方法,就是所有控件都給好高度,需要變換高度的給一個帶優(yōu)先級的高度約束,然后在tableview中這樣設(shè)置(已demo為例),一定要有預(yù)估高度和UITableViewAutomaticDimension

    var cellHeight:CGFloat = UITableViewAutomaticDimension // cell高
    var estimatedHeight:CGFloat = 50// 預(yù)估高度
/** 行高 */
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return cellHeight
    }
/** 預(yù)估高度 */
    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return estimatedHeight
    }

貼一下約束圖,如果兩個label都會變換高度的話 可以改優(yōu)先級,點Height Equals的Edit就可以設(shè)置優(yōu)先級了

大標題的高度固定為25

詳情Label的高度>=20,優(yōu)先級為1000

Controller

controller中只用關(guān)注model什么時候獲取數(shù)據(jù),創(chuàng)建什么樣的cell,什么時候刷新界面,點擊時怎么處理就好了

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    let viewModel = ZETableViewModel()
    let model = ZEVCModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false
        layoutSomething()
    }
    /**
     加載ViewModel,Model 刷新數(shù)據(jù)
     */
    func layoutSomething(){
        tableView.delegate = viewModel
        tableView.dataSource = viewModel
        viewModel.sectionCount = 1
        viewModel.cellHeight = UITableViewAutomaticDimension
        tableView.registerNib(UINib.init(nibName: "ZECell", bundle: nil), forCellReuseIdentifier: "ZECell")
        weak var weakSelf = self
        // 創(chuàng)建cell
        viewModel.cellRender = { indexPath,tablleView in
            let cell = tablleView.dequeueReusableCellWithIdentifier("ZECell", forIndexPath: indexPath) as! ZECell
            cell.bigTitleLabel.text = weakSelf?.model.dataArr[indexPath.row].bigTitle
            cell.contextLabel.text = weakSelf?.model.dataArr[indexPath.row].context
            return cell
        }
        // cell點擊事件
        viewModel.cellSlect = { indexPath,tablleView in
            print(weakSelf!.model.dataArr[indexPath.row].context)
        }
        // 模擬網(wǎng)絡(luò)請求
        model.getData { (success, status) in
            weakSelf!.viewModel.rawCount = weakSelf!.model.dataArr.count
            weakSelf!.tableView.reloadData()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

這樣做的優(yōu)點就是在Controller中很容易處理一些真正核心的步驟,不用寫大量的重復(fù)代碼.而且如果把ViewModel抽象好的話,整個工程的TableView都可以用這一個ViewModel,非常方便
最終形態(tài)可以做成這樣

掘金新版的設(shè)置界面

DEMO地址

本項目demo:https://github.com/Lafree317/ZEMVVM
OC版是一個比較完善的開源庫,大家可以去看一下,我這個是oc版的閹割版
OC版地址:https://github.com/youzan/SigmaTableViewModel

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容