How to show an alert from another class in Swift?

前端 未结 3 547
我寻月下人不归
我寻月下人不归 2021-02-02 02:11

I have a main class, AddFriendsController, that runs the following line of code:

ErrorReporting.showMessage(\"Error\", msg: \"Could not add student          


        
3条回答
  •  耶瑟儿~
    2021-02-02 02:48

    You can create extension method for UIApplication (for example) which will return your topViewController:

    extension UIApplication {
    
        static func topViewController(base: UIViewController? = UIApplication.sharedApplication().delegate?.window??.rootViewController) -> UIViewController? {
            if let nav = base as? UINavigationController {
                return topViewController(nav.visibleViewController)
            }
            if let tab = base as? UITabBarController, selected = tab.selectedViewController {
                return topViewController(selected)
            }
            if let presented = base?.presentedViewController {
                return topViewController(presented)
            }
    
            return base
        }
    }
    

    And then your class will look like this:

    class ErrorReporting {
    
        static func showMessage(title: String, msg: String) {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
            UIApplication.topViewController()?.presentViewController(alert, animated: true, completion: nil)
        }
    }
    

    Method need to be static to be able to call it as ErrorReporting.showMessage.

提交回复
热议问题