Search code examples
rx-swift

How to use RxSwift to implement the following logic with UITextfield?


The TextCode has a UItextField on the right side. The PassCode has a UItextField on the right side.

Use RxSwift to implement the following logic.
SelectAlertItem AlertViewControll sheet style has three options: A, B, C. Now I can implement the selection logic.

I don't know how to use RxSwift to implement the following logic.
The following is my key logic: Only when the selectedItem is B. TextCodeTextField text must be copied to PassCodeTextField at the end of editing.

In other word, SelectType is B, TextCodeTextField input "11111" and editingend, then PassCodeTextField will be "11111".

enter image description here

How to use RxSwift to implement the following logic with UITextfield?


Solution

  • Here's how to do it using my Cause Logic Effect architecture (with notes):

    
    import Cause_Logic_Effect
    import RxCocoa
    import RxSwift
    import UIKit
    
    final class ViewController: UIViewController {
        var textCodeField: UITextField!
        var selectTypeAction: UIButton!
        var selectTypeLabel: UILabel!
        var passCodeField: UITextField!
        let disposeBag = DisposeBag()
    }
    
    extension ViewController {
        func connect() {
            // when user taps the selectTypeAction, display an action sheet alert to
            // get the selection type from the user.
            let selectType = selectTypeAction.rx.tap
                .flatMapFirst(
                    presentScene(animated: true, over: selectTypeAction, scene: {
                        UIAlertController(
                            title: nil,
                            message: "Select Item:",
                            preferredStyle: .actionSheet
                        )
                            .scene { $0.connectChoice(choices: ["A", "B", "C"]) }
                    })
                )
                .share()
    
            // when the user selects "B" grab the last value entered in the
            // textCodeField and push it to the passCodeField
            selectType
                .compactMap { $0 }
                .filter { $0 == "B" }
                .withLatestFrom(textCodeField.rx.text)
                .bind(to: passCodeField.rx.text)
                .disposed(by: disposeBag)
    
            // when the user selects a value push the value to the selectTypeLabel
            selectType
                .bind(to: selectTypeLabel.rx.text)
                .disposed(by: disposeBag)
        }
    }