RxSwift How to add “clear all” UIButton to simple spreadsheet example

穿精又带淫゛_ 提交于 2020-01-03 03:15:05

问题


Here's the code from the RxSwift repo for a simple spreadsheet (adding three numbers):

Observable.combineLatest(number1.rx_text, number2.rx_text, number3.rx_text) { textValue1, textValue2, textValue3 -> Int in
        return (Int(textValue1) ?? 0) + (Int(textValue2) ?? 0) + (Int(textValue3) ?? 0)
    }
    .map { $0.description }
    .bindTo(result.rx_text)
    .addDisposableTo(disposeBag)

I want to add a "Clear all" UIButton, that will cause the three boxes to be reset to zero and the total also set to zero. In imperative style, very easy.

What is the correct way of adding this button in RxSwift?


回答1:


Here are a couple of ways off the top of my head.

Imperative

button.rx_tap
    .subscribeNext { [weak self] _ in
        self?.number1.text = ""
        self?.number2.text = ""
        self?.number3.text = ""
    }
    .addDisposableTo(disposeBag)

Note however, that this will not update the combineLatest Observable below until you change focus between fields. I haven't looked into why.

Using Variables

// Declared as a property
let variable1 = Variable<String>("")

// Back down in `viewDidLoad`
number1.rx_text
    .bindTo(variable1)
    .addDisposableTo(disposeBag)

variable1.asObservable()
    .bindTo(number1.rx_text)
    .addDisposableTo(disposeBag)

button.rx_tap
    .subscribeNext { [weak self] _ in
        self?.variable1.value = ""
        // and other variables as well..
    }
    .addDisposableTo(disposeBag)

Observable.combineLatest(variable1.asObservable(), ....

I've omitted showing the same code for variable2 and variable3, as you should probably make a two-way binding helper method if you go this route.



来源:https://stackoverflow.com/questions/38201532/rxswift-how-to-add-clear-all-uibutton-to-simple-spreadsheet-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!