[英]Subscription to a UIButton.rx.tap located in UITableViewCell within UITableViewDataSource
假設我在UITableViewCell
有一個UIButton
。 從UITableView
取出單元格后,我想訂閱UIButton.rx.tap
。 問題是,如果我的UITableViewCell
多次出列,訂閱將保留。 目前我通過在UITableViewCell
分配一個Disposable
屬性,在創建訂閱時設置它,並在UITableViewCell.prepareForReuse()
上調用Disposable.dispose()
來解決這個問題,但據我所知,以一種需要你的方式實現功能調用Disposable.dispose()
意味着你做錯了什么。
有沒有更好的方法來實現訂閱的唯一性而無需重新分配UIButton
?
另一個解決方案(不需要額外的庫或調用Disposable.dispose()
)是在單元格中有一個DisposeBag
,並在prepareForReuse
重新創建它,如此GitHub問題所示 :
//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
如果您的單元格中有更多按鈕(或您想要訂閱的其他Observable),它也會起作用。 您不必在單元格中為每個單元格創建一個新的Disposable
。
您可以在UITableViewCell
使用被動訂閱來正確使用Cell-Rx pod格式。 對於您的情況,您可以使用rx_reusableDisposeBag
,它將正確處理您的訂閱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.