防止tableviewCell上button点击事件重复订阅,
1.cell中添加
prepareForReuse()
方法,每次重用cell的时候都会调用这个方法,我们在这个方法里面释放之前绑定的disposeBag,重新生成一个新的disposeBag,具体实现如下:
//每次重用cell的时候都会释放之前的disposeBag,为cell创建一个新的dispose。保证cell被重用的时候不会被多次订阅,造成错误
override func prepareForReuse() {
super.prepareForReuse()
dispose = DisposeBag()
}
override func awakeFromNib() {
super.awakeFromNib()
//设置按钮点击事件
testMyBtn.rx.tap.subscribe(onNext: { (_) in
guard self.infoModel != nil else {
return
}
var model = self.infoModel
model?.name = "按钮1"
self.cellSub.onNext(model!)
}).disposed(by: dispose)
testMyBtn1.rx.tap.subscribe(onNext: { (_) in
guard self.infoModel != nil else {
return
}
var model = self.infoModel
model?.name = "按钮2"
self.cellSub.onNext(model!)
}).disposed(by: dispose)
}
viewController中设置如下
lazy var datasource = RxTableViewSectionedReloadDataSource<SectionModel<String,ZJReuseModel>>(configureCell: { (db, tableview, indexPath, model) -> UITableViewCell in
let cell = tableview.dequeueReusableCell(withIdentifier: "ZJReuseButtonCell") as! ZJReuseButtonCell
cell.infoModel = model
cell.cellSub.subscribe(onNext: { (index) in
let info = "我是第\(index)按钮"
let alert = UIAlertController.init(title: "你好", message: info, preferredStyle: .alert)
let action = UIAlertAction.init(title: "确定", style: .cancel, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}).disposed(by: cell.dispose)
return cell
})
最后附上测试代码:测试代码