AlertController is not in the window hierarchy

前端 未结 8 1737
北荒
北荒 2020-11-29 03:01

I\'ve just created a Single View Application project with ViewController class. I would like to show a UIAlertController from a function which is located inside my own class

8条回答
  •  醉梦人生
    2020-11-29 03:34

    You can use below function to call alert from any where just include these method in AnyClass

    class func topMostController() -> UIViewController {
            var topController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController
            while ((topController?.presentedViewController) != nil) {
                topController = topController?.presentedViewController
            }
            return topController!
        }
    
        class func alert(message:String){
            let alert=UIAlertController(title: "AppName", message: message, preferredStyle: .alert);
            let cancelAction: UIAlertAction = UIAlertAction(title: "OK", style: .cancel) { action -> Void in
    
            }
            alert.addAction(cancelAction)
            AnyClass.topMostController().present(alert, animated: true, completion: nil);
        }
    

    Then call

    AnyClass.alert(message:"Your Message")
    

提交回复
热议问题