Расширяемые ячейки Swift 5 RxDataSource

Я хочу передать расширяемый tableView со значения по умолчанию на Rx, но обнаружил проблему, связанную с тем, что не могу правильно использовать numberOfRownInSection.

Теперь логика такова... когда ваша структура имеет флаг isExpandable = false, количество строк равно 0

У меня есть tableView со статическими данными (структура будет представлена ​​ниже). HeaderView как заголовок и ячейки как расширяемое содержимое.

Переключить функцию:

func toggleCell(_ section: Int) {

    var indexPaths = [IndexPath]()

    for row in data[section].items.indices {
        let indexPath = IndexPath(row: row, section: section)
        indexPaths.append(indexPath)
    }

    let isExpanded = data[section].isExpanded
    data[section].isExpanded = !isExpanded

    if isExpanded {
        categoriesTableView.deleteRows(at: indexPaths, with: .none)
    } else {
        categoriesTableView.insertRows(at: indexPaths, with: .none)
    }

}

Делегат tableView по умолчанию:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: HomeViewCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
    cell.categoryLabel.text = data[indexPath.section].items[indexPath.row].title ?? ""
    return cell
}

func numberOfSections(in tableView: UITableView) -> Int {
    return data.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if !data[section].isExpanded {
        return 0
    }

    return data[section].items.count
}

Структура

var data: [CategoriesSectionData] = [CategoriesSectionData(header: "Elektro",            items: [CategoriesCellData(price: 12.99, title: "Gärtner 1"),
                                                                                                 CategoriesCellData(price: 15.30, title: "Gärtner 2"),
                                                                                                 CategoriesCellData(price: 25.99, title: "Gärtner 3")], isExpanded: false, icon: "home_menu_1"),
                                     CategoriesSectionData(header: "Gartenpflege",       items: [CategoriesCellData(price: 14.0, title: "Gärtner 1")], isExpanded: false, icon: "home_menu_2"),
                                     CategoriesSectionData(header: "Sanitär",            items: [], isExpanded: false, icon: "home_menu_3"),
                                     CategoriesSectionData(header: "Hausmeisterdienste", items: [], isExpanded: false, icon: "home_menu_4"),
                                     CategoriesSectionData(header: "Meisterprüfung",     items: [], isExpanded: false, icon: "home_menu_3"),
                                     CategoriesSectionData(header: "Gartenpflege",       items: [], isExpanded: false, icon: "home_menu_2"),
                                     CategoriesSectionData(header: "Sanitär",            items: [], isExpanded: false, icon: "home_menu_1"),
                                     CategoriesSectionData(header: "Hausmeisterdienste", items: [], isExpanded: false, icon: "home_menu_4")]

Чтобы передать это в Rx, я использовал следующий код, но у меня возникает ошибка при вставке/удалении строк, потому что я не хочу очищать свой источник данных и не могу установить numberOfRownInSection в значение not отображать ячейки с расширяемым флагом.

let dataSource = RxTableViewSectionedReloadDataSource<CategoriesSectionData>(
        configureCell: { ds, tv, indexPath, item in

            let cell: HomeViewCell = tv.dequeueReusableCell(forIndexPath: indexPath)
            cell.categoryLabel.text = item.title ?? ""
            return cell
        },

        titleForHeaderInSection: { ds, index in
            return ds.sectionModels[index].header
        }
    )

    self.dataSource = dataSource

    Observable.just(data)
        .bind(to: categoriesTableView.rx.items(dataSource: dataSource))
        .disposed(by: disposeBag)

    categoriesTableView.rx
        .setDelegate(self)
        .disposed(by: disposeBag)

person George Heints    schedule 19.11.2019    source источник


Ответы (1)


Попробуйте посмотреть репозиторий RxDataSources на GitHub. Есть пример, как это сделать. Вы можете привязать cellViewModels к tableview способом Rx

person Serban Coroiu    schedule 18.12.2019