-
Notifications
You must be signed in to change notification settings - Fork 2
Creating your first list
Create a view model for your cell that conforms to TableCellViewModel
. You should implement id: String
property. Implement rowHeight: CGFloat
if you need to setup specific cell height (UITableView.automaticDimension
is default).
struct StringCellViewModel: TableCellViewModel {
typealias TableCellType = StringCell
let id: String
let text: String
}
Create your cell that conforms to ConfigurableCell
. Override prepareForReuse
and recreate disposeBag
here. It guarantees that any subscriptions from a cell will be correctly disposed.
class StringCell: UITableViewCell, ConfigurableCell {
var disposeBag = DisposeBag()
func configure(with viewmodel: StringCellViewModel) {
textLabel?.text = viewmodel.text
}
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
}
Create your view model and put it into TableSectionModel
. Remember ids
should be unique in every section.
let stringItem = StringCellViewModel(id: "id", text: "Test")
let sections = [TableSectionModel(id: "sectionId", items: [stringItem])
Then just create TableDirector
and subscribe to sections using it. Also, don't forget to set director
as tableView
delegate.
let director = TableDirector()
Observable.just(sections)
.bind(to: tableView.rx.items(director: director))
.disposed(by: disposeBag)
tableView.rx.setDelegate(director)
.disposed(by: disposeBag)
Configuring UICollectionView
is quite similar. Moreover, you can reuse the same view model, just by implementing CollectionCellViewModel
protocol. Note that you must implement itemHeight
and itemWidth
. itemHeight
is just a simple CFloat
. But itemWidth
can be absolute and relative. Absolute means CFloat
value (just like itemHeight
). Relative is a size in percentage of the collectionView
's width.
extension StringCellViewModel: CollectionCellViewModel {
typealias CollectionCellType = StringCollectionCell
var itemWidth: CollectionItemWidth { .relative(percentage: 100) }
var itemHeight: CGFloat { 44 }
}
StringCollectionCell
looks pretty similar.
class StringCollectionCell: UICollectionViewCell, ConfigurableCell {
var disposeBag = DisposeBag()
func configure(with viewmodel: StringCellViewModel) {
textLabel?.text = viewmodel.text
}
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
}
Then put your viewModel into CollectionSectionModel
.
let stringItem = StringCellViewModel(id: "id", text: "Test")
let sections = [CollectionSectionModel(id: "sectionId", items: [stringItem])
And subscribe to sections using CollectionDirector
.
let director = CollectionDirector()
Observable.just(sections)
.bind(to: collectionView.rx.items(director: director))
.disposed(by: disposeBag)
collectionView.rx.setDelegate(director)
.disposed(by: disposeBag)
If you want to process some event in a cell check Events in Cells