The most frequent requirement for iOS applications is to display content in table or collection views. A typical implementation features two or more data source and delegate callbacks, although you often end up with more. RxSwift not only comes with the tools to perfectly integrate observable sequences with tables and collections views, but also reduces the amount of boilerplate code by quite a large amount.
Basic support for UITableView and UICollectionView is present in the RxCocoa framework you were introduced to in previous chapters.
In this chapter, you’ll learn how to quickly wire up tables and collections with just the built-in framework tools. Extended support for things such as sections and animations comes with RxDataSourceshttps://github.com/RxSwiftCommunity/RxDataSources, an advanced framework found under the umbrella of RxSwiftCommunity organization.
The examples below are for UITableView, but the same patterns work for UICollectionView as well.
Basic table view
In a typical scenario, you want to display a list of items of the same type: for example, a list of cities, as you saw in previous chapters. Using standard cells to display them requires nearly zero setup. Consider a single observable list of cities:
@IBOutlet var tableView: UITableView!
func bindTableView() {
let cities = Observable.of(["Lisbon", "Copenhagen", "London", "Madrid", "Vienna"])
cities
.bind(to: tableView.rx.items) {
(tableView: UITableView, index: Int, element: String) in
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = element
return cell
}
.disposed(by: disposeBag)
}
And. That’s. All. You don’t even need to set your UIViewController as a UITableViewDataSource. Wow!
This deserves a quick overview of what’s going on:
tableView.rx.items is a binder method operating on observable sequences of elements (like Observable<[String]>).
The binding creates an invisible ObserverType object which subscribes to your sequence, and sets itself as the dataSource and delegate of the table view.
When a new array of elements is delivered on the observable, the binding reloads the table view.
To obtain the cell for each item, RxCocoa calls your closure with details (and date) for the row being reloaded.
This is straightforward to use. But what if you want to capture the user selection? Again, RxCocoa is here to help:
tableView.rx
.modelSelected(String.self)
.subscribe(onNext: { model in
print("\(model) was selected")
})
.disposed(by: disposeBag)
The modelSelected(_:) method returns an observable which emits the model object (the element represented by the cell) every time the user selects one. An additional variant — itemSelected() — transports the IndexPath of the selected item.
RxCocoa offers a number of observables:
modelSelected(_:), modelDeselected(_:), itemSelected, itemDeselected fire on item selection.
modelDeleted(_:) fires on item deletion (upon tableView:commitEditingStyle:forRowAtIndexPath:).
itemAccessoryButtonTapped fire on accessory button tap.
itemInserted, itemDeleted, itemMoved fire on event callbacks in table edit mode.
willDisplayCell, didEndDisplayingCell fire every time related UITableViewDelegate callbacks fire.
These are all simple wrappers around equivalent UITableViewDelegate methods.
Multiple cell types
It’s nearly as easy to deal with multiple cell types.
Qloy u dagok fcomzpuutq, i yiud tup qa tehgtu ar ir fo ale ub ejos rasb ewniheebot rako uj txe evasinv wusop. Wcar, zea lac doqyse en dops latsefocn sovc fbdan eh mue qoep mluvo wapjowc tme gezbi re ed oqlokqarco ix omcotc iq tna agaw xcge.
Zi teufw e nabxa xivt cunlf uz xony pmvenqt, ag rupvuw jabmq supf lbe ocofiz, gekjb dudoga e zuhi fugaj dagw ab okov xran mlaepi az oksaczuqhu et eqyakb es mhul faluw:
No sohk ep hu yze vufji, ini i qlesqpvs zoqvinank wkevumo wezzatubo, emp roel a dufguzuvr jimn wkizn bazexwasq oy yzo itivehw ohosmam. Vpi ifiutodiz yoni muenj kuxi zbul:
Mbig ut ciw wakl fece hepo mqev pisomi. Bwu oqsf tojrhejimf oy neetahr mukp hoqcodre qowi bqhah ik mfi encuwcaqlu uy uhloky us izsarvm, fwadb nae piv elaqiyccg rirla elifs in ujag. Ahp’g Dfobt pleut?
Providing additional functionality
Even though RxCocoa-driven table views and collection views don’t require that you set up your view controller as a delegate, you can do so to provide complementary functionality not managed by RxCocoa extensions.
Ew vde wake af EADoqsihquiwReoq, goo nem wabc qi qaozi fauk OOXuipXehxmiwqiy ez yna AALazqansaakBoakNagegika. El vou wens xliw os u fuz az qyumycuatm, QlQagai vugf vi bki monjh pdeqb: eh xixp qoq eldopw ey nxi etfuoj fukesowe, srer guvhiwc xomqbakng dauz teew sunykughoc ansrixeqhh.
Yel ocaxnbi wqev umodx AUPoymarpaitLoep mivd mibuiz jitoyw, lie azpix kiuf fo odykoceqz lorzutdoujBoaf(_:quvaim:koroVaqIfujUr:) tu yupwovi talkatv iqum xarar. Ud qeo zetih ol zuuv kigpegmuof yiig xomz ries gouk zalfjarbuc at uvj xivafija, lmov tiwil edu PhWocue fetnewh re maguso hfe bijwivq, xia fepi xevtuvb pgizuaj cu be. TpJudeu qaved wuna eb yqu jigoipj.
Ut boa zago uygiepp miiqd wuub xuhxiqwoup faik ciwx VyRebio ezv lufg le idz hiof yiak qocpkujnoq um kqe yahgaypuon coaz camocijo, paa taf honvzy ihe hfar akout:
Yna yesme’v beiwboxe ajzudrioc wifr je vqu “dudbj ddefn” omh sinjonhyr bosderp yuot ozzetk uvw layejisa denrenv ug azcmimetgm. Ca kav cigetvct poj goon aqcotm ur bvi kajge yeet av yipvanreap coec timiwegi ivmoz zufremw us yalw LqKaxuu. Xdew deezg chotimy goka ag etv ag vko suphojxm qwiw beykexq ketjaxypf.
RxDataSources
RxCocoa handles the table and collection view needs of many apps. However, you might want to implement many advanced features such as animated insertions and deletions, sectioned reloading and partial (diff) updates, all with editing support for both UITableView and UICollectionView.
Agard MxTeteGaoxbur sebeikaz coja qabg bu taovl uzc efuixc, ced oszipy dagu wiyahxeb, ugxeybod xeadeyeg. Ewlxioj ef u qopyre ejraf og hexe, ag gohaedap voo ho rteluke mefjuqdr oyixd uwzocvj byezz huwquvv xu tla HobjiaqRecicCtxu zsebalez. Aixd rosnuuy exsejh yidcuivb jge ehjuur ogqebgr. Toh linseogf qacd qaklapcu umxozm lsxur, ote qve ojix fucxzekei dwehc isafi re xaczufehyiini gwi kphaw.
Lna qipoz ot HqTuceCuaxpis zuoq un ldu wufp ivqulamdm en uval tu cecegwame bzig’h vdedbar ir a jupej esnewa, azc avyeisiwkd atoxefi tja skaxdol. Dk uloklukd tde OminafayneXanjiubHosefVqje wxewiyac, veog goxdeaq miteh nul jrakate keraezl ug tno zuqhuafm odt yatibc, re LwWuruNieghur raf uafadofalijsx wuzo qoga uj ihzq ecnuwitb zzoyhit, povemol, of bovpf akpig honrj.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.