将 UITableViewCell 中的 UIButton 点击手势绑定到 viewModel 中的可观察对象
Binding UIButton tap gesture in UITableViewCell to observable in viewModel
在使用 RxSwift
和 MVVM 模式时,处理 UITableViewCell
中 UIButton
的点击手势的最佳方法是什么?我应该将它绑定到 viewModel
中的变量吗?
您可以在您的单元格中提供一个 tap observable 并从 vc 绑定它。
class SomeCell: UITableViewCell {
@IBOutlet var detailsButton : UIButton!
var detailsTap : Observable<Void>{
return self.detailsButton.rx.tap.asObservable()
}
}
然后在 vc:
private func bindTable(){
//Bind the table elements
elements.bind(to: self.table.rx.items) { [unowned self] (table, row, someModel) in
let cell = cellProvider.cell(for: table, at: row) //Dequeue the cell here (do it your own way)
//Subscribe to the tap using the proper disposeBag
cell.detailsTap
.subscribe(onNext:{ print("cell details button tapped")})
.disposed(by: cell.disposeBag) //Notice it's using the cell's disposableBag and not self.disposeBag
return cell
}
.disposed(by: disposeBag)
//Regular cell selection
self.table.rx
.modelSelected(SomeModel.self)
.subscribe(onNext:{ model in print("model")})
.disposed(by: self.disposeBag)
}
在使用 RxSwift
和 MVVM 模式时,处理 UITableViewCell
中 UIButton
的点击手势的最佳方法是什么?我应该将它绑定到 viewModel
中的变量吗?
您可以在您的单元格中提供一个 tap observable 并从 vc 绑定它。
class SomeCell: UITableViewCell {
@IBOutlet var detailsButton : UIButton!
var detailsTap : Observable<Void>{
return self.detailsButton.rx.tap.asObservable()
}
}
然后在 vc:
private func bindTable(){
//Bind the table elements
elements.bind(to: self.table.rx.items) { [unowned self] (table, row, someModel) in
let cell = cellProvider.cell(for: table, at: row) //Dequeue the cell here (do it your own way)
//Subscribe to the tap using the proper disposeBag
cell.detailsTap
.subscribe(onNext:{ print("cell details button tapped")})
.disposed(by: cell.disposeBag) //Notice it's using the cell's disposableBag and not self.disposeBag
return cell
}
.disposed(by: disposeBag)
//Regular cell selection
self.table.rx
.modelSelected(SomeModel.self)
.subscribe(onNext:{ model in print("model")})
.disposed(by: self.disposeBag)
}