【问题标题】:Subscribing to UIButton tap in a UICollectionViewCell in RxSwift?在 RxSwift 的 UICollectionViewCell 中订阅 UIButton 点击​​?
【发布时间】:2017-03-20 09:17:17
【问题描述】:

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

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

【问题讨论】:

  • 您是否使用过 XCode 调试器来仔细检查 self 是否不为零,以及警报控制器是否已成功实例化?这样您就可以尝试找出问题所在(是 Rx 问题,还是引用问题)。

标签: ios swift uibutton frp rx-swift


【解决方案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()
}

【讨论】:

    猜你喜欢
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多