协议声明与实现
protocol SHViewModelProtocol:UITableViewDataSource,UITableViewDelegate {
associatedtype ItemType
var dataArray:[ItemType] {set get}
}
protocol SHCellProtocol {
associatedtype ItemType
var model:ItemType? {set get}
mutating func updateData(dataArray:[ItemType],index:IndexPath);
}
extension SHCellProtocol{
mutating func updateData(dataArray:[ItemType],index:IndexPath) {
print("执行了====")
if dataArray.count > index.row {
self.model = dataArray[index.row]
}
}
}
class SHBaseTableCell<Element>: UITableViewCell,SHCellProtocol {
typealias ItemType = Element
var model:Element?
}
class SHBaseTableViewModel<Element>: NSObject,SHViewModelProtocol {
var dataArray: [Element] = [Element]()
var listView:UITableView?
typealias ItemType = Element
var registNibCells:[SHBaseTableCell<Element>.Type] = [SHBaseTableCell<Element>.Type]()
func bindViewModel(listView:UITableView,registNibCells:[SHBaseTableCell<Element>.Type]) {
self.listView = listView
self.registNibCells = registNibCells
for item in registNibCells {
let nib = UINib.init(nibName: "\(item.self)", bundle: nil)
listView.register(nib, forCellReuseIdentifier: "\(item.self)")
}
listView.dataSource = self
listView.delegate = self
}
func updateData(list:[Element]) {
self.dataArray = list
self.listView?.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellType = self.registNibCells.first!
let cell = tableView.dequeueReusableCell(withIdentifier: "\(cellType)", for: indexPath)
if var item = cell as? SHBaseTableCell<Element> {
item.updateData(dataArray: self.dataArray, index: indexPath)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
``
网友评论