控制器减负之分离数据源

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,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
    }()

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

Github地址:DataSource代码

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...