Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift: upgrade model state when textfield gets focus

Tags:

swift

rx-swift

I have a UIViewController with 3 UITextFields. 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?

like image 254
alexxjk Avatar asked May 01 '16 16:05

alexxjk


1 Answers

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)
    }
}
like image 195
solidcell Avatar answered Nov 15 '22 05:11

solidcell