0
1

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の勉強メモ】#1「ボタンのタップを検知してラベルの内容を変更する」

Posted at

この記事の目的

RxSwiftの使い方を学んでいくために簡単なサンプルを作成し記録する。
後から見直して頑張ります。
↓にサンプルコードを示します。

サンプル

import UIKit
import RxSwift
import RxCocoa

class ViewController: UIViewController {

    
    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var badButton: UIButton!
    var numberofGood = 0
    
    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        button.rx.tap
            .subscribe { (event) in
                self.buttonTapped()
            }
            .disposed(by: disposeBag)
        
        badButton.rx.tap
            .subscribe { (event) in
                self.badButtonTapped()
            }
            .disposed(by: disposeBag)
        
        label.text = String(0)
    }

    func buttonTapped() {
        
        numberofGood += 1
        label.text = String(numberofGood)
    }
    
    func badButtonTapped() {
        
        if numberofGood > 0{
            numberofGood -= 1
            label.text = String(numberofGood)
        }
    }
}

スクリーンショット 2020-11-29 20.35.48.png

サンプルコードの内容

サンプルコードは至ってシンプル。
画面左上のいいねボタンがタップされると画面中央の数値がインクリメントされ、
画面右上の悪いねボタンがタップされるとデクリメントされます。
画面収録 2020-11-29 20.13.19.gif

まとめ

RxSwiftを理解している人にとっては容易すぎる内容は承知の上で
引き続きメモ的な位置付けとして投稿していきたいと思います!。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?