订阅UIButton点击RxSwift中的UICollectionViewCell?

时间:2016-11-07 05:14:05

标签: ios swift uibutton frp rx-swift

我是RxSwift的新手,试图绕过它。我无法在单元格中获取UIButton,以便在按下时显示UIAlertController。

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)
 }

按下时没有任何反应。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

我实际上更喜欢在其子类上分配单元格按钮操作。问题是我认为每个单元格都应该有自己的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()
}