I have a ViewController
connect to a Xib file. In this Xib file I have a View, and inside this View, I have a TableView like so
I also have LeftTableViewCell
and RightTableViewCell
which connected to another Xib files.
Now I want to register LeftTableViewCell
and RightTableViewCell
in this TableView, so how to do this, my code always can not compiled.
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(LeftTableViewCell.self, forCellReuseIdentifier: LeftTableViewCell.reuseIdentifier)
// tableView.register(UINib(nibName: "LeftTableViewCell", bundle: nil), forCellReuseIdentifier: LeftTableViewCell.reuseIdentifier)
// tableView.register(UINib(nibName: "RightTableViewCell", bundle: nil), forCellReuseIdentifier: LeftTableViewCell.reuseIdentifier)
items.asObservable().bindTo(tableView.rx.items(cellIdentifier: LeftTableViewCell.reuseIdentifier, cellType: LeftTableViewCell.self)) { row, data, cell in
cell.data = data
}.addDisposableTo(disposeBag)
tableView.rx.modelSelected(String.self).subscribe { [unowned self] (event) in
switch event {
case .next(let element):
if let selectedRowIndexPath = self.tableView.indexPathForSelectedRow {
self.tableView.deselectRow(at: selectedRowIndexPath, animated: true)
}
break
default:
break
}
}.addDisposableTo(disposeBag)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Use the familiar register function and register each XIB to a different identifier.
tableView.register(UINib(nibName: "LeftTableViewCell", bundle: nil), forCellReuseIdentifier: "LeftCell")
tableView.register(UINib(nibName: "RightTableViewCell", bundle: nil), forCellReuseIdentifier: "RightCell")
In the cell factory:
.
items.asObservable()
.bindTo(tableView.rx.items) { (tableView, row, element) in
let indexPath = IndexPath(row: row, section: 0)
if row % 2 == 0 { // 1
let cell = tableView.dequeueReusableCell(withIdentifier: "LeftCell", for: indexPath) as! LeftTableViewCell // 2
// Configure the cell
return cell // 3
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "RightCell", for: indexPath) as! RightTableViewCell
// Configure the cell
return cell
}
}
.disposed(by: disposeBag)
screenshot
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With