2016-11-07 94 views
1

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

按下時沒有任何反應。我在這裏做錯了什麼?

+0

你使用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() 
}