RxElegantReuse 5.0.0

RxElegantReuse 5.0.0

TStrawberry 维护。



 
依赖
RxSwift~> 5.0
RxCocoa~> 5.0
 

  • TStrawberry

RxElegantReuse

CocoaPods Compatible Carthage Compatible Platform

一个优雅且基于 RxSwift 的方法来观察可重用视图(如 UITableViewCell、UICollectionViewCell)内的事件。

为什么

当观察来自 UITableViewCell 的可观察对象时,你是否感到有些不灵活?你可能需要进行以下工作

/// CustomCell.swift
class CustomCell: UITableViewCell {

    @IBOutlet weak var button: UIButton!
    
    var bag: DisposeBag = DisposeBag()
    
    override func prepareForReuse() {
        super.prepareForReuse()
        bag = DisposeBag()
    }
}

/// CustomViewController.swift
class CustomTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        data.bind(to: tableView.rx.items(cellIdentifier: "identifier", cellType: CustomCell.self), curriedArgument: {
            (index, data, cell) in
            ...
            cell.button.rx.tap
                .subscribe({ (event) in
                    /// Addd some code
                })
                .disposed(by: cell.bag) 
            ...
        })   
    }
}

如你所见,我们在 curriedArgument 闭包中观察了所有 Observables。或者我们可以将 cell.button.rx.tap 绑定到闭包外部的 Observer,从而编写更多代码。或许还有其他方式,但基本上没有本质区别。所以,让我们看看 RxElegantReuse。

依赖

要求

  • Swift 5
  • iOS 8+
  • tvOS 9+

安装

  • 使用CocoaPods:

    pod 'RxElegantReuse', '~> 5.0.0'
  • 使用Carthage:

    github "TStrawberry/RxElegantReuse" ~> 5.0.0
    

为保持与Swift和RxSwift相同的major版本号,因此没有1.x、2.x和3.x。

使用

RxElegantReuse仅为此特定场景提供几个API。

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    data.bind(to: tableView.rx.items(cellIdentifier: "identifier", cellType: CustomCell.self), curriedArgument: {
      [unowned tableView]
        (index, data, cell) in
        ...
        // Step 1 : Making the reusable view managed by its container(UITableView/UiCollectionView).
        cell.managed(by: tableView)
        ...
    })
    
    // Step 2 : Getting an Events instance through a Swift 4.0 KeyPath and it is an observable sequence.
    tableView.rx.events(\CustomCell.button.rx.tap)
        .subscribe(onNext: { (values) in            
            // Add some code
        })
        .disposed(by: bag)  
    ...
}

还有几个额外的API可以用于定制和方便的使用,等待您的尝试。

运行

carthage update --no-use-binaries --configuration Debug RxSwift

许可证

RxElegantReuse遵循MIT许可证。