Search code examples
iosswiftswiftbond

How can I add sections to my UITableViewCell?


How can I add sections to my UITableViewCell with the Bond framework?

 self.viewModel.items.bind(to: self.tableView) { (item, indexPath, tableView) -> UITableViewCell in
                      let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ListCell.self),
                                                               for: indexPath) as! ListCell
                       cell.item = item[indexPath.row]
                      return cell
                  }.dispose(in: self.bag)

Solution

  • You must write this class

    class  CustomSection<Changeset: SectionedDataSourceChangeset>: TableViewBinderDataSource<Changeset>, UITableViewDelegate where Changeset.Collection == Array2D <String, ListItemViewModel> {
    
            @objc func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
                return changeset?.collection[sectionAt: section].metadata
            }
    

    and in viewDidload of your ViewController you must call this function.

    private func setupViewModel() {  
            let sectionBindingDatSource: CustomSection = CustomSection<TreeChangeset>{ (changeset, indexPath, tableView) -> UITableViewCell in
                let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ListCell.self), for: indexPath) as! ListCell
                cell.item = changeset.sections[indexPath.section].items[indexPath.row]
    
                return cell
            }
            self.viewModel.sections.bind(to: self.tableView, using: sectionBindingDatSource)
        }
    

    and if you want to override function of TableViewDataSourse and customize section you must set delegate

    self.tableView.delegate = sectionBindingDatSource