美文网首页
RxSwift【UITableView plain样式实现】

RxSwift【UITableView plain样式实现】

作者: wsj_2012 | 来源:发表于2020-08-07 18:08 被阅读0次

本文讲解的是RxSwift UITableView的plain(只有一个section)样式的实现

1、工程依赖库

podfile文件添加依赖库

  pod 'RxSwift'
  pod 'RxCocoa'
  pod 'RxDataSources'

2、ViewController中添加如下代码

//
//  HomeViewController.swift
//  RxSwiftDemo
//
//  Created by wsj_2012 on 2020/8/7.
//  Copyright © 2020 wsj_2012. All rights reserved.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
import RxDataSources

class HomeViewController: UIViewController {
    
    let disposeBag = DisposeBag.init()
    
    let homeModel = HomeModel()

    lazy var tableView: UITableView = {
        let tableview = UITableView.init(frame: self.view.bounds,style: .plain)
        tableview.tableFooterView = UIView()
        tableview.register(RowViewCell.classForCoder(), forCellReuseIdentifier: "resuseID")
        tableview.rowHeight = 100
        return tableview
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "新闻"
        view.backgroundColor = .white
        // Do any additional setup after loading the view.
        
        setupSubViews()
        bindViewModel()
        updateData()
    }
    
    func setupSubViews() {
        view.addSubview(tableView)
    }
    
    func bindViewModel() -> Void {
        homeModel.plainItems.bind(to: tableView.rx.items(cellIdentifier: "resuseID", cellType: RowViewCell.self)){(row, model, cell) in
          cell.textLabel?.text = model.title
        }.disposed(by: disposeBag)

    }
    
    func updateData() {
        homeModel.updatePlainModels()
    }
  
}

3、ViewController中用到的HomeModel.swift类

//
//  HomeModel.swift
//  RxSwiftDemo
//
//  Created by wsj_2012 on 2020/8/7.
//  Copyright © 2020 wsj_2012. All rights reserved.
//

import UIKit
import RxSwift
import RxRelay

class HomeModel: NSObject {
   
    var plainItems = BehaviorRelay(value: [RowModel.Row.init()])
    
    // 模拟网络请求回来数据的更新数据操作
    func updatePlainModels() {
        var arr: [RowModel.Row] = []
        for i in 0...10 {
            let m = RowModel.Row(title: "标题\(i)", subTitle: "副标题\(i)")
            arr.append(m)
        }
        plainItems.accept(arr)
    }

}

4、ViewController类中的RowViewCell

RowViewCell.swift类自行创建,继承自UITableViewCell

相关文章

网友评论

      本文标题:RxSwift【UITableView plain样式实现】

      本文链接:https://www.haomeiwen.com/subject/jxhqdktx.html