Search code examples
swiftuicollectionviewuikitrx-swift

How to use RxSwift to draw the UICollectionView cells according to the number of data


I made a var sample = Public Subject <[]>() and I'm going to draw a vowel view with it. If the number of samples is 0, I would like to draw one collection View cell, and if it is more than one, I would like to draw according to the number of samples.

self.viewModel.sample
    .bind(to: collectionView.rx.items(
        cellIdentifier: "cell",
        cellType: Cell.self
    )) { index, item , cell in
        //
    }
    .disposed(by: disposeBag)

I only know how to implement it as above. What should I do?

This is my first time using RxSwift. I don't know what to do.


Solution

  • The answer by @son is great and should be accepted. Just for completeness, I will post this answer for those who want to show an "Empty View" instead of a single cell.

    The solution then is to give the table view a background view that represents what it looks like when empty, then you can do this:

    items
        .bind(to: tableView.rx.items(cellIdentifier: "Cell")) { _, item, cell in
            cell.textLabel?.text = item
        }
        .disposed(by: disposeBag)
    
    tableView.backgroundView = createEmptyView()
    
    items
        .map { !$0.isEmpty }
        .bind(to: tableView.backgroundView!.rx.isHidden)
        .disposed(by: disposeBag)