如何使用RxSwift将数据预先添加到tableview或collectionview

时间:2017-02-11 15:52:37

标签: ios swift uitableview swift3 rx-swift

我可以看到我可以使用Subject PublishVariable将新元素添加到表视图或集合视图中,并在最后显示正确但如果需要在表视图的开头添加新数据。怎么办?

如何将数据添加到可观察序列中,以便新数据显示在tableview或集合视图的顶部???

2 个答案:

答案 0 :(得分:2)

您可以使用combineLatest运算符。

最初,newData是一个空数组,当您向其添加数据时,它会显示在tableView的顶部

    let data = [
        "A New Hope",
        "The Empire Strikes Back",
        "Return of the Jedi"
    ]

    let obsData = Observable.just(data)

    let newData = [
        "The Phantom Menace",
        "Attack of the Clones",
        "Revenge of the Sith"
    ]
    let obsNewData = Observable.just(newData)

    let items = Observable.combineLatest(obsData, obsNewData){
        $1+$0 
    }     

    items.bindTo(tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, film, cell) in
        cell.textLabel?.text = film
    }
    .addDisposableTo(disposeBag)

答案 1 :(得分:0)

全面了解我在寻找什么

import UIKit
import RxSwift
import RxCocoa

struct Person {
    let name : String
    let age : Int

}
class ViewController: UIViewController {
    let personArray = [
        Person(name: "name1", age: 11),
        Person(name: "name2", age: 12),
        Person(name: "name3", age: 13)
    ]

    let disposeBag = DisposeBag()
    var items : Observable<[Person]>!

    @IBOutlet weak var mytable: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        items = Observable.just(personArray)
        bindData()
    }

    @IBAction func prependButtonAction(_ sender: UIButton) {
        let newPersonArray = [
            Person(name: "name -3", age: 11),
            Person(name: "name -4", age: 12)
        ]
        prependData(dataToPrepend: newPersonArray)
    }

    @IBAction func appendButtonAction(_ sender: UIButton) {
        let newPersonArray = [
            Person(name: "name 6", age: 11),
            Person(name: "name 7", age: 12)
        ]
        appendData(dataToAppend : newPersonArray)
    }



    private func bindData() {
        mytable.dataSource = nil
        items.bindTo(mytable.rx.items(cellIdentifier: "cell")) { (row, person, cell) in
            if let cellToUse = cell as? TableViewCell {
                cellToUse.label1.text = person.name
                cellToUse.label2.text = "\(person.age)"
            }
        }.addDisposableTo(disposeBag)
    }

    private func prependData(dataToPrepend : [Person]) {
        let newObserver = Observable.just(dataToPrepend)
        items = Observable.combineLatest(items, newObserver) {
            $1+$0
        }
        bindData()
    }


    private func appendData(dataToAppend : [Person]) {
        let newObserver = Observable.just(dataToAppend)
        items = Observable.combineLatest(items, newObserver) {
            $0+$1
        }
        bindData()
    }
}