控制器减负之分离数据源

前端之家收集整理的这篇文章主要介绍了控制器减负之分离数据源前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Tableview在工程中使用频率非常高,那么对应的数据源也会频繁的出现的工程中。可以将这部分分离到单独的类中 ( 这个类可以复用到工程中 ) ,这样控制就可以减少一部分的代码量。闲话少说,上代码

DataSource中的数据源方法

  1. //MARK: -UITableViewDataSource
  2. func numberOfSections(in tableView: UITableView) -> Int {
  3. return itemsArray!.count
  4. }
  5.  
  6. func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
  7.  
  8. return itemsArray![section].count
  9.  
  10. }
  11.  
  12. func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  13.  
  14. let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: identifierArray![indexPath.section] )!
  15.  
  16. //获取相应的模型数据
  17. let item = itemAt(indexpath: indexPath)
  18.  
  19. //执行回调
  20. cellBlock!(cell,item,indexPath)
  21.  
  22. return cell
  23.  
  24. }

TableView中设置数据源代码

  1. //MARK: - lazy load tableView
  2. lazy var tableView:UITableView = {
  3. let tableView:UITableView = UITableView(frame: CGRect(x: 0,y: 0,width: UIScreen.main.bounds.size.width,height: UIScreen.main.bounds.size.height),style: .grouped)
  4.  
  5. var cellOneData = [AnyObject]()
  6.  
  7. var cellTwoData = [AnyObject]()
  8.  
  9. for i in 0..<5 {
  10. cellOneData.append("我是组一中第\(i)行的数据" as AnyObject)
  11. }
  12.  
  13. for i in 0..<5 {
  14. cellTwoData.append("我和组一长的很像但我是组二" as AnyObject)
  15. }
  16.  
  17. //分离数据源
  18. self.dataSource = DataSource(itemsArray: [cellOneData,cellTwoData],identifiers: [self.tableCellOneID,self.tableCellTwoID],cellBlock: { (cell,indexPath) in
  19.  
  20. //TableViewCellOne和TableViewCellTwo就是简单的继承了一下UITableViewCell
  21. if indexPath.section == 0 {
  22. cell.textLabel?.text = item as? String
  23. } else {
  24. cell.textLabel?.text = item as? String
  25. }
  26.  
  27. })
  28.  
  29. //直接把对象赋值给tableView.dataSource不行,没有保存对象
  30. tableView.dataSource = self.dataSource
  31.  
  32. //注册两个cell
  33. tableView.register(TableViewCellOne.self,forCellReuseIdentifier: self.tableCellOneID)
  34.  
  35. tableView.register(TableViewCellTwo.self,forCellReuseIdentifier: self.tableCellTwoID)
  36.  
  37. return tableView
  38. }()

如果对您有帮助,Star一下吧

Github地址:DataSource代码

猜你在找的Swift相关文章