假设我在 UIButton
中有一个 UITableViewCell
。
从 UITableView
出队后,我想订阅 UIButton.rx.tap
。问题是,如果我的 UITableViewCell
多次出队,订阅将保留。目前我通过在我的 Disposable
中分配一个 UITableViewCell
属性,在创建订阅时设置它,并在 Disposable.dispose()
上调用 UITableViewCell.prepareForReuse()
来解决这个问题,但是据我所知,以需要你调用 Disposable.dispose()
的方式实现功能意味着你正在做有事吗。
有没有更好的方法来实现订阅的唯一性而不重新分配 UIButton
?
最佳答案
另一种解决方案(不需要额外的库或调用 Disposable.dispose()
)是在单元格中有一个 DisposeBag
并在 prepareForReuse
中重新创建它,如本 GitHub issue 中所建议的:
//in the cell
private(set) var disposeBag = DisposeBag()
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
//in the data source
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! DiaryItemCell
cell.commentButton.rx_tap
.subscribeNext{
}.addDisposableTo(cell.disposeBag)
return cell
如果您的单元格中有更多按钮(或您想要订阅的其他 Observables),它也将起作用。您不必在单元格中为每个单元格创建新的
Disposable
。关于ios - 订阅位于 UITableViewDataSource 内 UITableViewCell 中的 UIButton.rx.tap,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41060254/