Tableview在工程中使用频率非常高,那么对应的数据源也会频繁的出现的工程中。可以将这部分分离到单独的类中 ( 这个类可以复用到工程中 ) ,这样控制就可以减少一部分的代码量。闲话少说,上代码:
DataSource中的数据源方法
- func numberOfSections(in tableView: UITableView) -> Int {
- return itemsArray!.count
- }
-
- func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
-
- return itemsArray![section].count
-
- }
-
- func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
-
- let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: identifierArray![indexPath.section] )!
-
-
- let item = itemAt(indexpath: indexPath)
-
-
- cellBlock!(cell,item,indexPath)
-
- return cell
-
- }
TableView中设置数据源代码
- lazy var tableView:UITableView = {
- let tableView:UITableView = UITableView(frame: CGRect(x: 0,y: 0,width: UIScreen.main.bounds.size.width,height: UIScreen.main.bounds.size.height),style: .grouped)
-
- var cellOneData = [AnyObject]()
-
- var cellTwoData = [AnyObject]()
-
- for i in 0..<5 {
- cellOneData.append("我是组一中第\(i)行的数据" as AnyObject)
- }
-
- for i in 0..<5 {
- cellTwoData.append("我和组一长的很像但我是组二" as AnyObject)
- }
-
-
- self.dataSource = DataSource(itemsArray: [cellOneData,cellTwoData],identifiers: [self.tableCellOneID,self.tableCellTwoID],cellBlock: { (cell,indexPath) in
-
-
- if indexPath.section == 0 {
- cell.textLabel?.text = item as? String
- } else {
- cell.textLabel?.text = item as? String
- }
-
- })
-
-
- tableView.dataSource = self.dataSource
-
-
- tableView.register(TableViewCellOne.self,forCellReuseIdentifier: self.tableCellOneID)
-
- tableView.register(TableViewCellTwo.self,forCellReuseIdentifier: self.tableCellTwoID)
-
- return tableView
- }()
如果对您有帮助,Star一下吧