LoginSignup
1
1

More than 1 year has passed since last update.

【Swift】コードでアラートを閉じる

Last updated at Posted at 2022-09-09

はじめに

たぶん普通の事なんだと思いますが、初心者すぎて悩んだので記録しておきます。

実装

ボタンでアラートを表示して、アプリがバックグラウンドになったらアラートを閉じます。

import UIKit

class ViewController: UIViewController {

    private var alert: UIAlertController!

    override func viewDidLoad() {
        super.viewDidLoad()

        // バックグラウンド監視
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(background),
            name: UIApplication.willEnterForegroundNotification,
            object: nil
        )
    }

    // アラートを表示する
    @IBAction private func alertButtonTapped(_ sender: Any) {
        alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert)
        let button = UIAlertAction(title: "OK", style: .default)
        alert.addAction(button)
        self.present(alert, animated: true)
    }
    
    // アラートを閉じる
    @objc private func background() {
        alert.dismiss(animated: true)
    }
}

おわり

最初に定義しておくなんて技思いつきません

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