//
// RXSwiftViewController.swift
// RXFunction
//
// Created by 王木木 on 16/10/27.
// Copyright © 2016年 王木木. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class RXSwiftViewController: UIViewController {
let tableView: UITableView = UITableView(frame: UIScreen.mainScreen().bounds, style: .Plain)
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<User, User>>()
let bag: DisposeBag = DisposeBag()
let reuseIdentifier = "\(RxTableViewCell.self)"
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.registerClass(RxTableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
dataSource.configureCell = {
section, tableView, indexPath, _ in
let cell = tableView.dequeueReusableCellWithIdentifier(self.reuseIdentifier, forIndexPath: indexPath) as! RxTableViewCell
cell.tag = indexPath.row
let model = section.sectionModels[indexPath.section]
cell.user = model.items[indexPath.row]
print(model.model.name)
return cell
}
getUsers()
.bindTo(tableView.rx_itemsWithDataSource(dataSource))
.addDisposableTo(self.bag)
self.tableView.rx_itemSelected.subscribeNext {
self.tableView.deselectRowAtIndexPath($0, animated: true)
}.addDisposableTo(disposeBag)
tableView.rx_setDelegate(self).addDisposableTo(bag)
}
func getUsers() -> Observable<[SectionModel<User, User>]> {
return Observable.create { (observer) -> Disposable in
let users = User(name: "韩杰")
let han = [
User(name: "jie"),
User(name: "jie"),
User(name: "jie"),
User(name: "jie"),
User(name: "jie")]
let section = [SectionModel(model: users, items: han),
SectionModel(model: users, items: han)]
observer.onNext(section)
observer.onCompleted()
return AnonymousDisposable{}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension RXSwiftViewController: UITableViewDelegate {
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let model = self.dataSource.numberOfSectionsInTableView(tableView)
guard model != 0 else {
return nil
}
let label = UILabel()
label.backgroundColor = UIColor.brownColor()
label.text = self.dataSource.sectionAtIndex(section).model.name
return label
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100
}
}
/*
* model
*/
struct User {
var name: String
}
/*
* UITableViewCell
*/
class RxTableViewCell: UITableViewCell {
var user: User? {
willSet {
let string = "\(newValue!.name)我觉得没必要纠结着不放"
backgroundColor = tag % 2 == 0 ? UIColor.lightGrayColor() : UIColor.whiteColor()
textLabel?.text = string
textLabel?.numberOfLines = 0
}
}
}