在RxSwift的UICollectionViewCell中订阅UIButton tap?
问题描述:
我是RxSwift的新手,试图围绕它来包裹我的头。我在按下UIAlertController时在单元格中显示UIButton时遇到了问题。在RxSwift的UICollectionViewCell中订阅UIButton tap?
private func setupCellConfiguration() {
bookListViewModel.data
.bindTo(collectionView.rx.items(cellIdentifier: BookListCell.Identifier, cellType: BookListCell.self)) { [unowned self] (row, element, cell) in
cell.configureForBook(book: element)
cell.moreButton.rx.tap.subscribe { [weak self] in
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {(action) in
self?.dismiss(animated: true, completion: nil)
}
alertController.addAction(cancelAction)
let destroyAction = UIAlertAction(title: "Delete", style: .destructive) { (action) in
}
alertController.addAction(destroyAction)
self?.present(alertController, animated: true)
}
.addDisposableTo(self.disposeBag)
}
.addDisposableTo(disposeBag)
}
按下时没有任何反应。我在这里做错了什么?
答
我其实更喜欢在其子类上指定单元格按钮操作。问题是我认为每个单元应该有它自己的disposeBag,每次重用时都应该重新初始化。
例子:有没有对代码进行测试,如果有任何问题,让我知道
private func setupCellConfiguration() {
bookListViewModel.data
.bindTo(collectionView.rx.items(cellIdentifier: BookListCell.Identifier, cellType: BookListCell.self)) { [unowned self] (row, element, cell) in
cell.delegate = self
cell.configureForBook(book: element)
}
.addDisposableTo(disposeBag)
}
// Your Cell Class
var disposeBag = DisposeBag()
var delegate: UIViewController?
func configureForBook(book: Book) {
self.moreButton.rx.tap.subscribe { [unowned self] in
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {(action) in
self?.dismiss(animated: true, completion: nil)
}
alertController.addAction(cancelAction)
let destroyAction = UIAlertAction(title: "Delete", style: .destructive) { (action) in
}
alertController.addAction(destroyAction)
self.delegate?.present(alertController, animated: true)
}
.addDisposableTo(self.disposeBag)
}
override func prepareForReuse() {
disposeBag = DisposeBag()
}
你使用Xcode的调试器仔细检查,如果自己不为零,如果警报控制器被实例化成功?通过这种方式,您可以尝试隔离问题所在(是Rx问题,还是引用问题)。 – iwillnot