Aleksander Aleksic
Aleksander Aleksic

Reputation: 1360

RxSwift format text

I am new to RxSwift but I am trying to use RxSwift with the MVVM patter to format some text. I have a textfield where I want the user to write in their credit card number, and as they write I want to format it.

So when they write "6789430078303201" I want to format it to: "6789 4300 7830 3201"

Any suggestions on how to do this?

Aleksander Aleksic

Upvotes: 1

Views: 551

Answers (3)

Predrag Samardzic
Predrag Samardzic

Reputation: 3019

Think what you described could be solved like this (not sure about formatting code itself):

textField.rx.controlEvent(.editingChanged)
            .subscribe(onNext: { [weak self] _ in
                guard let self = self, let text = self.textField.text else { return }
                let formatedText = text.replacingOccurrences(of: " ", with: "").enumerated().compactMap({ $0 % 4 == 0 ? " \($1)" : "\($1)" }).joined()
                self.textField.text = formatedText
            })
            .disposed(by: disposeBag)

If you want MVVM for this, maybe something along these lines:

    textField.rx.text
        .orEmpty
        .distinctUntilChanged()
        .bind(to: viewModel.inputText)
        .disposed(by: disposeBag)

    viewModel.outputText
        .bind(to: textField.rx.text)
        .disposed(by: disposeBag)

And in your viewModel:

class ViewModel {
    var inputText = BehaviorRelay<String>(value: "")
    var outputText = BehaviorRelay<String>(value: "")
    private let disposeBag = DisposeBag()

    init() {
        inputText
            .subscribe(onNext: { [weak self] (text) in
                guard let self = self else { return }
                let formatedText = text.replacingOccurrences(of: " ", with: "").enumerated().compactMap({ $0 % 4 == 0 ? " \($1)" : "\($1)" }).joined()
                self.outputText.accept(formatedText)
            })
            .disposed(by: disposeBag)
    }
}

Upvotes: 2

Trash
Trash

Reputation: 11

For what you want, you need to implement the UITextField delegate https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619599-textfield?language=objc . This is a more correct option. You can of course format the text inside the VM and give it to textField, but there will be problems with the cursor if the user wants to edit the value in the middle

Upvotes: 1

Maxim Volgin
Maxim Volgin

Reputation: 4077

I suppose .window(4) can help with the splitting part.

Upvotes: 0

Related Questions