2016-11-07 3 views
1

私はRxSwiftを初めて使っています。私はUIAlertControllerが押されたときにそれを表示するために、セル内でUIButtonを取得するのに問題がありました。RxSwiftのUICollectionViewCellでUIButtonタップを購読しますか?

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

押されても何も起こりません。私はここで間違って何をしていますか?

+0

を知っているあなたは、自己がnilでなかった場合は二重チェックするためにXCodeのデバッガを使用しており、警告コントローラが正常にインスタンス化された場合は?そうすれば、どこに問題があるのか​​を突き止めることができます(Rxの問題なのか、それとも参照する問題なのか)。 – iwillnot

答えて

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() 
} 
関連する問題