0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RxSwiftを使ってみた

Posted at

1.はじめに

RxSwiftを使ったことがないので、初めて使ってみました。よく採用の必要技術に書かれているので、触っていた方がいいかと思いました。また現在働いている場所でもRxSwiftを使用しているので必要性を感じていました。

2.実装 TextFieldに入力された文字をラベルに反映する

・RxSwiftを使わない場合(通常のデリゲートを使用)

ViewController
import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newText = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? string
        label.text = newText
        return true
    }
}

・RxSwiftを使う場合

ViewController
import UIKit
import RxSwift
import RxCocoa

class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var label: UILabel!

    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.rx.text.orEmpty
            .bind(to: label.rx.text)
            .disposed(by: disposeBag)
    }
}

RxCocoa の rx.text を使用し、テキスト変更を監視。
.bind(to:) を使い、textField のテキストを label.text に自動的にバインド。

RxSwift を使うとコードを簡潔にでき、非同期処理をする時に便利です。

3.おわりに

現在私が開発しているIDNectにはRxSwiftは使用されていません。ただ、RxSwiftを使用するとコードの量が減り、見やすくなるので今後コードを変更する際に導入しようと思いました!

IDNectはゲームIDを簡単に管理・共有!ワンタップでIDコピー、QRコードでフレンド追加、AIでID自動認識。SNS登録やメモ機能も充実!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?