1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RxSwiftでUITextFieldの最大文字数を設定する

Last updated at Posted at 2021-01-04
        //TextFieldの最大文字数設定
        textField.rx.text
            .map { text in
                if let text = text, text.count > 4 {
                    return String(text.prefix(4))
                } else {
                    return text ?? ""
                }
            }
            .bind(to: textField.rx.text) // 既に入力されているのと同じ数字を入力した場合、nextイベントは流れないので無限ループする事はない
            .disposed(by: disposeBag)

補足

  • 試していませんが、日本語入力の場合はこれだとうまくいかない可能性があるので別途考慮が必要になると思われます。
  • textField.rx.controlEvent(.editingChanged)なども使えます。

参考

RxSwift/RxCocoa: prevent UITextField from having more than … characters
[iOS] UITextFieldの最大文字数を設定する
【Swift】 UITextFieldに文字数制限を設ける方法

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?