elce
elce

Reputation: 312

Subscribing to UIButton tap in a UICollectionViewCell in RxSwift?

I'm new to RxSwift, trying to wrap my head around it. I was having trouble getting a UIButton in a cell to show a UIAlertController when it's pressed.

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

Nothing happens when it's pressed. What am I doing wrong here?

Upvotes: 1

Views: 2799

Answers (1)

Kris Julio
Kris Julio

Reputation: 26

I actually prefer to assign cell button action on its subclass. The problem is I think every cell should have it's own disposeBag and it should reinitialize every time it is reused.

Example: Haven't tested on code, if there's any problem let me know

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

Upvotes: 1

Related Questions