简体   繁体   English

Rxswift更新Tableview单元格值

[英]Rxswift Update Tableview cell value

I am able to bind an Observable sequence of data to a table. 我能够将可观察的数据序列绑定到表。 Now lets say i have a button on each cell which on click changes the label of that cell to new value. 现在让我们说我在每个单元格上都有一个按钮,单击该按钮会将该单元格的标签更改为新值。 How to do this ? 这个怎么做 ?

I have done so far as follows 我到目前为止已经做了如下

I have created an @IBAction for that button in the cell pointing class 我在单元格指向类中为该按钮创建了@IBAction

then i am doing 然后我在做

label.text = "new text"

but when i scroll down then scroll up, the label show previous value not the new value 但是当我向下滚动然后向上滚动时,标签显示以前的值而不是新的值

previously when i use array and set each value to a cell i used to update that array item and called tableview.reloadData . 以前,当我使用array并将每个值设置为一个单元格时,我用来更新该数组项并称为tableview.reloadData

how can i do this in RxSwift?? 我如何在RxSwift中做到这一点?

I have done so far 到目前为止我已经做过

tableview.dataSource = nil (then)
myData.bindTo ... (bind again)

This does not seem to me the right way. 在我看来,这不是正确的方法。 so what is the appropriate way to deal with this?? 那么解决这个问题的合适方法是什么?

I am able to achive this with RxSwiftCommunity Action 我可以通过RxSwiftCommunity Action实现这一目标

https://github.com/RxSwiftCommunity/Action

ViewController ViewController

variable.asObservable().bindTo(mytable.rx.items(cellIdentifier: "cell")) { (row, person, cell) in
            if let cellToUse = cell as? TableViewCell {
                cellToUse.person = Variable(person)
                cellToUse.button1.rx.action = cellToUse.action
            }
            }.addDisposableTo(disposeBag)

and in cell 并在细胞中

class TableViewCell: UITableViewCell {

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var button1: UIButton!

    let disposeBag = DisposeBag()
    let action = CocoaAction { input in
        return .just(input)
    }

    var person : Variable<Person>!{
        didSet {
            self.updateUI()
        }
    }

    private func updateUI(){
        person.asObservable()
            .subscribe(onNext: {
                person in
                let name : Observable<String> = Observable.of(person.name)
                let age : Observable<String> = Observable.of("\(person.age)")
                _ = name.bindTo(self.label1.rx.text)
                _ = age.bindTo(self.label2.rx.text)
            }).addDisposableTo(disposeBag)

        action.elements
            .asObservable()
            .subscribe(onNext: {
                _ in
                self.label2.text = "asd"

            }).addDisposableTo(disposeBag)
    }
}

like before not sure if this is the right way but it worked for me 像以前不确定这是否是正确的方法,但是对我有用

thanks to ( https://rxswift.slack.com/messages/@fpillet ) for showing me the way 感谢( https://rxswift.slack.com/messages/@fpillet )向我展示了方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM