订阅位于UITableViewDataSource中的UITableViewCell中的UIButton.rx.tap [英] Subscription to a UIButton.rx.tap located in UITableViewCell within UITableViewDataSource

查看:203
本文介绍了订阅位于UITableViewDataSource中的UITableViewCell中的UIButton.rx.tap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 UITableViewCell 中有 UIButton
UITableView 中取出单元格后,我想订阅 UIButton.rx.tap 。问题是如果我的 UITableViewCell 多次出列,订阅将保留。目前我通过在 UITableViewCell 中分配 Disposable 属性来解决此问题,在创建订阅时设置它,并调用 UITableViewCell.prepareForReuse()上的Disposable.dispose(),但据我所知,以某种方式实现功能要求你打电话给 Disposable.dispose()暗示你做错了。

Let's say I have a UIButton in a UITableViewCell. After dequeuing the cell from the UITableView I want to subscribe to the UIButton.rx.tap. The issue is that if my UITableViewCell is dequeued multiple times, the subscriptions would retain. Currently I solve this problem by allocating a Disposable property in my UITableViewCell, setting it when the subscription is create, and calling Disposable.dispose() on UITableViewCell.prepareForReuse(), however as far as I understand implementing features in a way that requires you to call Disposable.dispose() implies that you are doing something wrong.

有没有更好的方法完成订阅的唯一性而无需重新分配 UIButton

Is there any better way to accomplish uniqueness of the subscription without reallocating UIButton?

推荐答案

另一种解决方案(不需要额外的库或调用 Disposable.dispose())是在 DisposeBag 中单元格并在 prepareForReuse 中重新创建它,如此 GitHub问题

Another solution (which doesn't require an additional library or calling Disposable.dispose()) is to have a DisposeBag in the cell and re-create it in prepareForReuse, as suggested in this 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

如果您的单元格中有更多按钮(或您想要订阅的其他Observable),它也会起作用。您不必在单元格中为每个单元创建一个新的 Disposable

It will also work if you have more buttons (or other Observables which you want to subscribe to) in your cell. You won't have to create a new Disposable in the cell itself for each of them.

这篇关于订阅位于UITableViewDataSource中的UITableViewCell中的UIButton.rx.tap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆