Swift - 自定义UIAlertController,带ActionHandler


一、自定义方法

func showAlertWithActionHandler(title: String?, message: String?, preferredStyle: UIAlertControllerStyle = .alert, defaultHandler: (() ->Void)? = nil, cancelHandler: (() -> Void)? = nil)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
    
    let defaultAction = UIAlertAction(title: "好的", style: .default) { (alert) in
        defaultHandler!()
    }
    alert.addAction(defaultAction)
    
    if cancelHandler != nil
    {
        let cancelAction = UIAlertAction(title: "取消"), style: .cancel) { (alert) in
            cancelHandler!()
        }
        alert.addAction(cancelAction)
    }
    
    // 获取当前显示的 ViewController
    let theViewControllerYouSee = UIViewController.currentViewController()
    
    theViewControllerYouSee?.present(alert, animated: true, completion: nil)
}

二、 获取当前显示的 ViewController

extension UIViewController
{
    // 获取当前显示的 ViewController
    class func currentViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController?
    {
        if let nav = base as? UINavigationController
        {
            return currentViewController(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController
        {
            return currentViewController(base: tab.selectedViewController)
        }
        if let presented = base?.presentedViewController
        {
            return currentViewController(base: presented)
        }
        return base
    }
}

你可能感兴趣的:(Swift - 自定义UIAlertController,带ActionHandler)