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
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,532評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,252評論 4 61
  • 紀初拿出鑰匙打開家門的時候,紀親夏正坐在餐桌旁吃早餐,夾了煎蛋和培根肉的三明治咬了一半,抬起頭看著他。 “爸,你回...
    青空宇宙閱讀 137評論 0 0
  • 雖然這只是一個小小的招聘會,可能在以后的人生道路上會司空見慣,但是對于一些人而言這里就是機會!!想成為一名出色的開...
    牛肉丸閱讀 313評論 0 1