How to register show 2 custom cells alternately with RxSwift

2k views Asked by At

My ThirdViewController is in a Xib file, it has a tableView. I also have 2 cells in another xib files, I want to show 2 custom cells alternately with RxSwift. How to do this. Here is my code:

import UIKit
import RxSwift
import RxCocoa

class ThirdViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    let items: Variable<[String]> = Variable(["Test 2", "Test 3", "Test 1", "Test 4", "Test 5"])

    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        tableView.register(UINib(nibName: "LeftTableViewCell", bundle: nil), forCellReuseIdentifier: LeftTableViewCell.reuseIdentifier)
        tableView.register(UINib(nibName: "RightTableViewCell", bundle: nil), forCellReuseIdentifier: RightTableViewCell.reuseIdentifier)

        items.asObservable().bindTo(tableView.rx.items(cellIdentifier: LeftTableViewCell.reuseIdentifier, cellType: LeftTableViewCell.self)) { row, data, cell in
            cell.data = data
            }.addDisposableTo(disposeBag)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
1

There are 1 answers

2
HNK On
items.asObservable()
    .bindTo(tableView.rx.items) { (tableView, row, element) in
        let indexPath = IndexPath(row: row, section: 0)

        if row % 2 == 0 {
            // or some other logic to determine which cell type to create

            let cell = tableView.dequeueReusableCell(withIdentifier: LeftTableViewCell.reuseIdentifier, for: indexPath) as! LeftTableViewCell
            // Configure the cell
            return cell
        }
        else {
            let cell = tableView.dequeueReusableCell(withIdentifier: RightTableViewCell.reuseIdentifier, for: indexPath) as! RightTableViewCell
            // Configure the cell
            return cell
        }

    }
    .disposed(by: disposeBag)