一、概述
在OC的轮子中,使用一个RETableviewManager的轮子,核心原理是数据驱动页面,cell-item 一一对应,对UITableview页面的封装。
只要写好对应item和cell类,然后注册,交给manager即可,构建完整的页面;同时一些cell和item是可以被不同列表进行复用,只要给不同的item即可。
本人觉得项目使用效果还不错,因此写了个swift版本。
TBD:目前还在持续完善中...
二、做了一些优化
-
Item 和 cell的绑定,只支持registerClass的方式。
鼓励先注册,后续直接复用使用,避免新人错误。
实际项目中使用nib或xib很少,基本都是纯代码编写,因此简化(实在有需要的,后续再扩展)。 -
Item 和 cell 对应关系,通过Item的类方法返回
open class var cellClass: AnyClass { return SZTableViewCell.self }
- cell的高度,进行属性缓存,同时提供方法放到Item中
open class func calcCellHeight() -> Float { return 40.0 }
- cell的生命周期做了调整,新增
didUpdate方法,同时方法新增入参item
避免内部在使用属性。
protocol SZTableViewCellLifeCircel { // 首次创建调用 func didLoad(_ item: SZTableViewItem?) // 更新的时候调用, func didUpdate(_ item: SZTableViewItem?) // will display func willAppear(_ item: SZTableViewItem?) // end display func didDisappear(_ item: SZTableViewItem?) }
- 去掉原框架中的外部delegate
实际需要自己实现代理的场景很少,即使需要,是否也失去manager的功能;因此先不提供。
三、基本的使用方法
1、自定义 SZTableViewCell 和 SZTableViewItem 的子类
class ImageTitleCell: SZTableViewCell { lazy var titleLbl: UILabel = { let lbl = UILabel() lbl.text = "" lbl.textColor = .blue lbl.font = .systemFont(ofSize: 16) return lbl }() lazy var iconImgV: UIImageView = { let imgV = UIImageView() imgV.image = UIImage.init(named: "facebook") return imgV }() // 加载一次,cell创建 override func didLoad(_ item: SZTableViewItem?) { super.didLoad(item) if let cellItem = item as? ImageTitleCellItem { print("\(#function) \(cellItem.title)") self.iconImgV.frame = CGRect(x: 5, y: 5, width: 50, height: 50) self.contentView.addSubview(self.iconImgV) self.titleLbl.frame = CGRect(x: 60, y: 5, width: 150, height: 20) self.contentView.addSubview(self.titleLbl) } } // cell数据的更新 override func didUpdate(_ item: SZTableViewItem?) { if let cellItem = item as? ImageTitleCellItem { print("\(#function) \(cellItem.title)") self.titleLbl.text = cellItem.title } } // cell will display override func willAppear(_ item: SZTableViewItem?) { } // cell did end display override func didDisappear(_ item: SZTableViewItem?) { } } class ImageTitleCellItem : SZTableViewItem { var title: String = "" // 返回对应的cell override class var cellClass: AnyClass { return ImageTitleCell.self } // 返回Cell的高度 override func calcCellHeight() -> Float { return 80.0 } }
2、创建Manager
// ViewController lazy var tableview: UITableView = { let tblV = UITableView(frame:self.view.bounds, style:.plain) return tblV }() // manager let tblManager: SZTableViewManager = SZTableViewManager() self.view.addSubview(self.tableview) // 关联tableview tblManager.bindTableView(self.tableview) tblManager.registerList([ SZTitleCellItem.self, ImageTitleCellItem.self ]) // 创建section let section: SZTableViewSection = SZTableViewSection.init() let item = SZTitleCellItem() item.title = "TitleCell \(i)" item.action.selected = { (_ vi: SZTableViewItem? ,_ tblMgr: SZTableViewManager) in if let cellItem = vi as? SZTitleCellItem { print("click: \(cellItem.title)") } } section.addItem(item) tblManager.addSection(section)