代码基于swift4.0.
效果:
由于这里用的是纯代码实现,还不知道再RxSwift中如何修改cell的类型。所以只能显示歌曲名。如果用sb实现,可以直接在sb里面设置成带detail信息的cell。
-
代码结构
model
struct XXMusic {
let name: String //歌名
let singer: String //演唱者
init(name: String, singer: String) {
self.name = name
self.singer = singer
}
}
//实现 CustomStringConvertible 协议,方便输出调试
extension XXMusic: CustomStringConvertible {
var description: String {
return "name:\(name) singer:\(singer)"
}
}
- viewModel
struct XXMusicListViewModel {
let data = Observable.just([
XXMusic(name: "无条件", singer: "陈奕迅"),
XXMusic(name: "你曾是少年", singer: "S.H.E"),
XXMusic(name: "从前的我", singer: "陈洁仪"),
XXMusic(name: "在木星", singer: "朴树"),
])
}
- controller
import UIKit
import RxSwift
import RxCocoa
class XXMusicViewController: UIViewController {
let contentTableView = UITableView()
let musicViewModel = XXMusicListViewModel()
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
musicViewModel.data
.bind(to: contentTableView.rx.items(cellIdentifier: "musicCell")) {_, music, cell in
cell.textLabel?.text = music.name
cell.detailTextLabel?.text = music.singer//这里设置无效,后续改进
}.disposed(by: disposeBag)
contentTableView.rx.modelSelected(XXMusic.self).subscribe(onNext: {music in
print("selected music info : \(music)")
}).disposed(by: disposeBag)
}
func setupUI() {
navigationItem.title = "Music"
contentTableView.frame = CGRect(x: 0, y: 64, width: view.frame.width, height: view.frame.height - 64)
contentTableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "musicCell")
view.addSubview(contentTableView)
automaticallyAdjustsScrollViewInsets = false //防止tableView自动内容下移
}
}