alexxjk alexxjk - 5 months ago 63
Swift Question

RxSwift: upgrade model state when textfield gets focus

I have a

UIViewController
with 3
UITextField
s. Every time either of the fields gets focus, I want to set a new text value for a tip label above. What is the best way to achieve this with
RxSwift
?

Answer

This does what you're looking for. Any time a UITextField would send a textFieldDidBeginEditing: delegate message, you instead get an Observable for that. Then you map that Observable into the correct string for that text field. Then combine all 3 of those Observables into just one, where the latest event is from the text field that most recently called that delegate message. Then you bind that value to the tooltip's text.

import UIKit
import RxSwift
import RxCocoa

class ViewController: UIViewController {
    let disposeBag = DisposeBag()

    @IBOutlet weak var tooltip: UILabel!
    @IBOutlet weak var textField1: UITextField!
    @IBOutlet weak var textField2: UITextField!
    @IBOutlet weak var textField3: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let textField1Text = textField1.rx_controlEvent(.EditingDidBegin)
            .map { "text field 1 message" }

        let textField2Text = textField2.rx_controlEvent(.EditingDidBegin)
            .map { "text field 2 message" }

        let textField3Text = textField3.rx_controlEvent(.EditingDidBegin)
            .map { "text field 3 message" }

        Observable.of(textField1Text, textField2Text, textField3Text).merge()
            .bindTo(tooltip.rx_text)
            .addDisposableTo(disposeBag)
    }
}