前言
在OC中成熟的框架已經有很多了,但是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! // 創建cell的block
var cellSlect:ZECellSelectBlock? // 選中cell的block
var cellHeight:CGFloat = UITableViewAutomaticDimension
var estimatedHeight:CGFloat = 50// 預估高度
var sectionCount:Int = 0// 區數
var rawCount:Int = 0// 行數
/** 區數 */
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return sectionCount
}
/** 行數 */
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
}
/** 預估高度 */
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中,這里寫了一個模擬網絡請求的方法
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: "獲取數據成功")
}
var someData = [
[
"bigTitle":"我是大標題",
"context":"我是一個超長超長超長超長超長超長超長超長超長超長超長超長超長超長的內容"
]
]
}
View
這里僅用一個Cell來表示View,可以講一下通過AutoLayout自動計算cell高度的方法,就是所有控件都給好高度,需要變換高度的給一個帶優先級的高度約束,然后在tableview中這樣設置(已demo為例),一定要有預估高度和UITableViewAutomaticDimension
var cellHeight:CGFloat = UITableViewAutomaticDimension // cell高
var estimatedHeight:CGFloat = 50// 預估高度
/** 行高 */
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return cellHeight
}
/** 預估高度 */
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return estimatedHeight
}
貼一下約束圖,如果兩個label都會變換高度的話 可以改優先級,點Height Equals的Edit就可以設置優先級了
Controller
controller中只用關注model什么時候獲取數據,創建什么樣的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 刷新數據
*/
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
// 創建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)
}
// 模擬網絡請求
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.
}
}
這樣做的優點就是在Controller中很容易處理一些真正核心的步驟,不用寫大量的重復代碼.而且如果把ViewModel抽象好的話,整個工程的TableView都可以用這一個ViewModel,非常方便
最終形態可以做成這樣
DEMO地址
本項目demo:https://github.com/Lafree317/ZEMVVM
OC版是一個比較完善的開源庫,大家可以去看一下,我這個是oc版的閹割版
OC版地址:https://github.com/youzan/SigmaTableViewModel