RxSwift: state of the update model when the text field receives focus

I have UIViewControllerwith 3 UITextFields. Every time a field gets focus, I want to set a new text value for the caption above. What is the best way to achieve this using RxSwift?

+4
source share
1 answer

It does what you are looking for. Every time UITextFieldsends a message to the delegate textFieldDidBeginEditing:, instead you get Observable. Then you match this Observablewith the correct line for this text box. Then combine all 3 of these Observers into only one, where the last event is from the text box that was recently called this delegate message. Then you bind this value to the tooltip 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)
    }
}
+8
source

All Articles