控制器减负之分离数据源

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

DataSource中的数据源方法


   //MARK: -UITableViewDataSource
    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中设置数据源代码

    //MARK: - lazy load 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, item, indexPath) in
            
            //TableViewCellOne和TableViewCellTwo就是简单的继承了一下UITableViewCell
            if indexPath.section == 0 {
                cell.textLabel?.text = item as? String
            } else {
                cell.textLabel?.text = item as? String
            }
            
        })
        
        //直接把对象赋值给tableView.dataSource不行,没有保存对象
        tableView.dataSource = self.dataSource
        
        //注册两个cell
        tableView.register(TableViewCellOne.self, forCellReuseIdentifier: self.tableCellOneID)
        
        tableView.register(TableViewCellTwo.self, forCellReuseIdentifier: self.tableCellTwoID)
        
        return tableView
    }()

Github地址:DataSource代码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,925评论 25 709
  • iOS网络架构讨论梳理整理中。。。 其实如果没有APIManager这一层是没法使用delegate的,毕竟多个单...
    yhtang阅读 10,673评论 1 23
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,323评论 18 399
  • 我的村庄,今夜有美丽的月光 你看多美,你看多好 回胃的牛嚼,稍盹的狗和声音 小溪中,生命一直在生长 我在倾听 我的...
    梁伯益阅读 1,801评论 4 0
  • 今天的话题是汽车改装,汽车改装一般是改两个地方一是外观(也就是改车型)二是改动力。入门级的汽车改装爱好者,只...
    巫山烤漆阅读 2,720评论 0 2

友情链接更多精彩内容