An elegant and RxSwift-based way to observe events inside of reusable views like UITableViewCell, UICollectionViewCell.
Did you feel a little ungainly when you observe an Observable which comes from a UITableViewCell? You maybe have to complete some work like this:
/// 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)
...
})
}
}
As you can see, we observe all the Observables in the curriedArgument closure.
Or we can make cell.button.rx.tap
binding to a Observer outside of the curriedArgument closure, with more code.
There maybe other ways,but no essential difference.So let's move to RxElegantReuse.
- Swift 5
- iOS 8+
- tvOS 9+
-
Using CocoaPods:
pod 'RxElegantReuse', '~> 5.0.0'
-
Using Carthage:
github "TStrawberry/RxElegantReuse" ~> 5.0.0
For keeping same major version number with Swift and RxSwift, so no 1.x, 2.x and 3.x.
RxElegantReuse provides only several API for this specific scene.
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)
...
}
Several extra API for customization and convenience are waiting for your try.
carthage update --no-use-binaries --configuration Debug RxSwift
RxElegantReuse is under MIT license.