【发布时间】: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