Yurochka
Yurochka

Reputation: 31

Different cells CollectionView rxswift

Good evening. Tell me please I need to make such an implementation Have: CollectionView Rxswift The maximum number of cells is 6 If there are less than 6 elements in a certain array, then the first cells are filled with one type (by the number of elements in the array), and the rest with other cells.

collectionView.register(UINib(nibName: "PhotoCollectionCell", bundle: nil), forCellWithReuseIdentifier: "PhotoCell")
collectionView.register(UINib(nibName: "EmptyCollectionCell", bundle: nil), forCellWithReuseIdentifier: "EmptyCell")

Upvotes: 3

Views: 2914

Answers (2)

Charlie Cai
Charlie Cai

Reputation: 301

You need to import RxDataSources in case you want different cell type.

        // TableView Cell Nib Register
        tableView.register(R.nib.meChatCell)
        tableView.register(R.nib.otherChatCell)

        vm.output.chats
        .bind(to: tableView.rx.items){(tv, row, item) -> UITableViewCell in

            if item.userId == 0 {
                let cellIdentifier = R.reuseIdentifier.meChatCell.identifier
                let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: IndexPath.init(row: row, section: 0)) as! MeChatCell
                cell.vm = item
                return cell
            } else {
                let cellIdentifier = R.reuseIdentifier.otherChatCell.identifier
                let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: IndexPath.init(row: row, section: 0)) as! OtherChatCell
                cell.vm = item
                return cell
            }

        }.disposed(by: disposeBag)
}

Upvotes: 3

Boska
Boska

Reputation: 31

Please check collectionView.rx.items in UICollectionView+Rx.swift from RxCocoa Here is the example from code itselft

   let items = Observable.just([
             1,
             2,
             3
         ])

         items
         .bind(to: collectionView.rx.items) { (collectionView, row, element) in
            let indexPath = IndexPath(row: row, section: 0)
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell
             cell.value?.text = "\(element) @ \(row)"
             return cell
         }
         .disposed(by: disposeBag)

You can dequeue whatever cell you want based on the index of the row or type of the data, just like the way we did in DataSource

Upvotes: 3

Related Questions