我們通常使用tableview的時(shí)候要做一件事
在viewdidload中
self.tablview.register(cellClass, forCellReuseIdentifier:"cell")
self.tablview.register(HeaderFooterViewClass, forHeaderFooterViewReuseIdentifier:"header")
然后在
func tableView(_ tableView: UITableView, cellForRowAt indexPath:IndexPath)-> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
return cell!
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header")!
header.setValue(item, forKey: "model")
self.registerEventforSectionHeader(header: header,model: item)
return header
}
如果一個(gè)列表存在多種cell或者多種header 通常的做法是
func tableView(_ tableView: UITableView, cellForRowAt indexPath:IndexPath)-> UITableViewCell {
if self.dataList[indexPath.row] is Person {
let cell:Cell1 = tableView.dequeueReusableCell(withIdentifier: "cell1")
cell.viewModel=self.dataList[indexPath.row]
return cell!
}else {
let cell:Cell2 = tableView.dequeueReusableCell(withIdentifier: "cell2")
cell.viewModel=self.dataList[indexPath.row]
return cell!
}
}
既然數(shù)據(jù)源是是self.dataList 那么為什么我還要用string作為cell的id來獲取cell呢
為什么不使用model的class類型來幫綁定cell和header呢
說干就干
使用swift 的extends 或者oc的category
extension UITableView {
func registerCellClass(cellClass:AnyClass,modelClass:AnyClass) {
self.register(cellClass, forCellReuseIdentifier:String(describing:modelClass.self) )
}
func registerCellNib(nib:UINib,modelClass:AnyClass){
self.register(nib, forCellReuseIdentifier: String(describing:modelClass.self))
}
///headerClass必須繼承UITableViewHeaderFooterView
func registerHeaderClass(headerClass:AnyClass,modelClass:AnyClass) {
self.register(headerClass, forHeaderFooterViewReuseIdentifier: String(describing:modelClass.self))
}
func registerHeaderNib(nib:UINib,modelClass:AnyClass){
self.register(nib, forHeaderFooterViewReuseIdentifier: String(describing:modelClass.self))
}
}
這樣我就能在調(diào)用的時(shí)候就可以
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item=self.getRealDataSourceModel(indexPath: indexPath)
let cellKey=String(describing:item.classForCoder.self)
let cell = tableView.dequeueReusableCell(withIdentifier: cellKey)
cell?.setValue(item, forKey: "model")
return cell!
}
如果再自己寫一個(gè)tableviewController的基類
把cell和model數(shù)據(jù)源的關(guān)系綁定好
那么實(shí)現(xiàn)一個(gè)帶列表的界面
heightforIndexpath cellforIndexpath numberOfRow numberOfSection都可以不用寫了
只需要注冊一下cell和model的關(guān)系,傳一個(gè)dataList進(jìn)去 一切都做好了
具體例子我已經(jīng)做出來了可以看看我封裝的swift開發(fā)框架
https://github.com/manondidi/swiftArch
基類:PagingViewController
demo: PagingOffsetIdDemoViewController和PaingTalbeDemoViewController