UITableView是我們經常用的一個控件,而且在開發過程中經常需要設置dataSource和delegate,然後實現相應的協議:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
}
在學習了RxSwift之後,我們可以寫更優雅的代碼實現上面的功能,下面來看一個簡單demo,實現一個簡單的tableView列表展示簡單數據
class ViewController: UIViewController {
let disposeBag = DisposeBag()
lazy var tableView: UITableView = {
let table = UITableView()
table.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
return table
}()
override func viewDidLoad() {
super.viewDidLoad()
addTableView()
bindTableView()
}
func addTableView() {
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.left.top.bottom.right.equalToSuperview()
}
}
func bindTableView() {
// 1 初始化數據源
let items = Observable.just((0...30).map {"\($0)" })
// 2 綁定數據源到tableView
items.bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)){ (row, element, cell) in
cell.textLabel?.text = "\(element)"
}
.disposed(by: disposeBag)
// 3 設置點擊事件
tableView.rx.modelSelected(String.self).subscribe(onNext: {
print("tap index: \($0)")
}).disposed(by: disposeBag)
}
}
由上面代碼可知,我們僅僅只需要將數據源綁定到tableView上即可,這樣可以實現相同的效果,而且代碼看起來更簡短。