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.

[SwiftUI] コード(ViewModelなど)からAlertを表示する方法

Last updated at Posted at 2021-03-16

概要

SwiftUIでView以外のコードからAlertを表示する方法を調べました。
最前面のViewControllerからAlertControllerをpresentすれば良さそうです。

実装

AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    static var me: AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }

    /// 最前面のViewControllerを取得する
    /// https://stackoverflow.com/a/57169802/4791194
    /// https://stackoverflow.com/a/42580981/4791194
    func topController() -> UIViewController? {
        let keyWindow = UIApplication.shared.connectedScenes
                .filter({$0.activationState == .foregroundActive})
                .map({$0 as? UIWindowScene})
                .compactMap({$0})
                .first?.windows
                .filter({$0.isKeyWindow}).first
        var topController = keyWindow?.rootViewController
        while let presentedViewController = topController?.presentedViewController {
            topController = presentedViewController
        }
        return topController
    }
}

呼び出し例

HogeViewModel.swift
let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
AppDelegate.me.topController()?.present(alert, animated: true, completion: nil)

参考

関連

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?