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?

More than 3 years have passed since last update.

【Swift】オブザーバパターン イベント通知

Posted at

イベント通知

Swiftにおけるイベント通知のパターン

  • デリゲートパターン
  • クロージャ
  • オブザーバーパターン

オブザーバパターン

実装方法

  1. 通知を受けるオブジェクトにNotification型の値を引数に持つメソッドを実装する
  2. NotificationCenterクラスに通知を受け取るオブジェクトを登録する
  3. NotificationCenterクラスに通知を投稿する

ソースコード

    override func viewDidAppear(_ animated: Bool) {
        //ここでUIKeyboardWillShowという名前の通知のイベントをオブザーバー登録をしている
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        //ここでUIKeyboardWillHideという名前の通知のイベントをオブザーバー登録をしている
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    // UIKeyboardWillShow通知を受けて、実行される関数
    @objc func keyboardWillShow(notification: NSNotification) {
    }
    // UIKeyboardWillShow通知を受けて、実行される関数
    @objc func keyboardWillHide(notification: NSNotification) {
    }
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?