控制器减负之分离数据源

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

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

Github地址:DataSource代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

俯仰一世_1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值