【问题标题】:UITableViewCell containing a UICollectionView using RxSwift包含使用 RxSwift 的 UICollectionView 的 UITableViewCell
【发布时间】:2018-05-18 08:01:49
【问题描述】:

我开始在我的 iOS 项目中使用 RxSwift,并且我有一个带有自定义 UITableViewCell 子类的 UITableView。在那个子类中,我有一个UICollectionView

使用RxSwift 填充tableview 非常完美,我正在使用RxSwift 的另一个扩展名(RxDataSources

这是我的做法:

    self.dataSource = RxTableViewSectionedReloadDataSource<Section>(configureCell: {(section, tableView, indexPath, data)  in
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCellWithCollectionView

        switch indexPath.section {
        case 0:
            cell.collectionViewCellNibName = "ContactDataItemCollectionViewCell"
            cell.collectionViewCellReuseIdentifier = "contactDataItemCellIdentifier"
        case 1, 2:
            cell.collectionViewCellNibName = "DebtCollectionViewCell"
            cell.collectionViewCellReuseIdentifier = "debtCellIdentifier"
        default:
            break
        }
        cell.registerNibs(indexPath.section, nativePaging: false, layoutDirection: indexPath.section != 0 ? .horizontal : .vertical)

        let cellCollectionView = cell.collectionView!

        data.debts.asObservable().bind(to: cellCollectionView.rx.items(cellIdentifier: "debtCellIdentifier", cellType: DebtCollectionViewCell.self)) { row, data, cell in
            cell.setup(debt: data)
        }


        return cell

    })

这确实有效。但是当tableview 单元格从屏幕上滚动并重新出现时,就会出现问题。这会从上面触发代码块并让应用程序崩溃

    data.debts.asObservable().bind(to: cellCollectionView.rx.items(cellIdentifier: "debtCellIdentifier", cellType: DebtCollectionViewCell.self)) { row, data, cell in
        cell.setup(debt: data)
    }

在同一个 tableview 单元格上被调用两次(有趣的是,即使 Xcode 崩溃也没有任何痕迹)。

我能做些什么来避免这种情况?

编辑:

我找到了一个解决方案,但我必须承认我对此并不满意......这是这个想法(经过测试并且有效)

我在课堂上定义了另一个Dictionary

var boundIndizes = [Int: Bool]()

然后我在绑定周围创建一个if,如下所示:

if let bound = self.boundIndizes[indexPath.section], bound == true {
    //Do nothing, content is already bound
} else {
    data.debts.asObservable().bind(to: cellCollectionView.rx.items(cellIdentifier: "debtCellIdentifier", cellType: DebtCollectionViewCell.self)) { row, data, cell in
        cell.setup(debt: data)
        }.disposed(by: self.disposeBag)
    self.boundIndizes[indexPath.section] = true
}

但我不敢相信没有“更清洁”的解决方案

【问题讨论】:

  • 在您的固定代码中,您将diposable 存储在disposeBag 上,但不是在您的第一个代码中。您是否将其存储在任何地方?
  • @AndreCarvalho 是的,我在有和没有disposeBag 的情况下都试过了,没有区别

标签: ios swift uitableview uicollectionview rx-swift


【解决方案1】:

问题是每次单元格出列时,您都将data.debts 绑定到单元格内的collectionView。

我建议您将与您的data.debts 相关的逻辑移动到单元格本身并声明一个var disposeBag: DisposeBag,您可以在prepareForReuse 上重新实例化它。参考this answer

【讨论】:

  • 你说得对,这很有意义......非常感谢
猜你喜欢
  • 2021-12-21
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多