微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

控制器减负之分离数据源

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代码

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐