#はじめに
前回の続きです!
合わせてこちらもご覧ください!
#GitHub
今回のリポジトリは以下のGitHubのExampleRxSwiftです。
#実装
以下のように、テキストフィールドの文字数に応じて残りの入力可能文字数がわかるというものをつくってみましょう。
RxSwiftを使わない場合は簡単ですね。
import UIKit
final class ExampleViewController: UIViewController {
@IBOutlet private weak var nameTextField: UITextField!
@IBOutlet private weak var nameLabel: UILabel!
@IBOutlet private weak var addressTextField: UITextField!
@IBOutlet private weak var addressLabel: UILabel!
private let maxNameTextFieldSize = 10
private let maxAddressTextFieldSize = 50
private let limitText: (Int) -> String = {
return "あと\($0)文字"
}
override func viewDidLoad() {
super.viewDidLoad()
nameTextField.addTarget(self,
action: #selector(nameTextFieldEditingChanged(sender:)),
for: .editingChanged)
addressTextField.addTarget(self,
action: #selector(addressTextFieldEditingChanged(sender:)),
for: .editingChanged)
}
@objc func nameTextFieldEditingChanged(sender: UITextField) {
guard let changedText = sender.text else { return }
let limitCount = maxNameTextFieldSize - changedText.count
nameLabel.text = limitText(limitCount)
}
@objc func addressTextFieldEditingChanged(sender: UITextField) {
guard let changedText = sender.text else { return }
let limitCount = maxAddressTextFieldSize - changedText.count
addressLabel.text = limitText(limitCount)
}
}
RxSwiftを使うとこのようになります。
import UIKit
import RxSwift
import RxCocoa
import RxOptional
final class RxExampleViewController: UIViewController {
@IBOutlet private weak var nameTextField: UITextField!
@IBOutlet private weak var nameLabel: UILabel!
@IBOutlet private weak var addressTextFiled: UITextField!
@IBOutlet private weak var addressLabel: UILabel!
private let maxNameTextFieldSize = 10
private let maxAddressTextFieldSize = 50
private let limitText: (Int) -> String = {
return "あと\($0)文字"
}
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
nameTextField.rx.text
.map { [weak self] text -> String? in
guard let text = text else { return nil }
guard let maxNameTextFieldSize = self?.maxNameTextFieldSize else { return nil }
let limitCount = maxNameTextFieldSize - text.count
return self?.limitText(limitCount)
}
.filterNil()
.bind(to: nameLabel.rx.text)
.disposed(by: disposeBag)
addressTextFiled.rx.text
.map { [weak self] text -> String? in
guard let text = text else { return nil }
guard let maxAddressTextFieldSize = self?.maxAddressTextFieldSize else { return nil }
let limitCount = maxAddressTextFieldSize - text.count
return self?.limitText(limitCount)
}
.filterNil()
.bind(to: addressLabel.rx.text)
.disposed(by: disposeBag)
}
}
#おわりに
まだまだ続きます!
次回