利用協議擴展封裝UIAlertView

原創文章轉載請注明出處

The rabbit by Dennis Heidrich on 500px.com
The rabbit by Dennis Heidrich on 500px.com

接上一篇利用協議擴展封裝ProgressHUD,這幾天琢磨著逐步把BaseViewController中的方法挪出來,進一步給BaseViewController減肥。

iOS 8開始蘋果推薦使用UIAlertController替代原有的UIAlertView,關于UIAlertView的使用,推薦參看UIAlertView-Blocks。今天要介紹的是我封裝的一個UIAlertController的方法,利用Swift的協議擴展和默認參數,簡化了UIAlertController的使用。

import Foundation

// MARK: - UIAlertViewable

protocol UIAlertViewable {
    func showAlertAction(title title: String?, message: String?, okTitle: String, cancelTitle: String?, okAction: ((Void) -> Void)?, cancelAction: ((Void) -> Void)?)
}

extension UIAlertViewable where Self: UIViewController {
    
    func showAlertAction(title title: String? = nil, message: String? = nil,
                               okTitle: String = NSLocalizedString("ok", comment: "確定"), cancelTitle: String? = nil,
                               okAction: ((Void) -> Void)? = nil, cancelAction: ((Void) -> Void)? = nil) {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        
        let okAction = UIAlertAction(title: okTitle, style: .Default) { _ in
            if let handler = okAction {
                handler()
            }
        }
        alertController.addAction(okAction)
        
        if let title = cancelTitle {
            let cancelAction = UIAlertAction(title: title, style: .Cancel) { _ in
                if let handler = cancelAction {
                    handler()
                }
            }
            alertController.addAction(cancelAction)
        }
        
        presentViewController(alertController, animated: true, completion: nil)
    }
    
}

如何使用?

class LoginViewController: UIViewController, UIAlertViewable {
    ...
}
//只顯示確定
showAlertAction(title: title, message: message, okTitle: "確定")

//顯示確定和取消
showAlertAction(title: title, message: message, 
                okTitle: "確定", cancelTitle: "取消")
                
//顯示確定和取消,并帶有響應方法
showAlertAction(title: title, message: message, 
                okTitle: "確定", cancelTitle: "取消",        
                okAction: { [unowned self] _ in
                    //to do
                },
                cancelAction: { [unowned self] _ in
                    //to do
                })

我是咕咕雞,一個還在不停學習的全棧工程師。
熱愛生活,喜歡跑步,家庭是我不斷向前進步的動力。

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

推薦閱讀更多精彩內容

  • 敕勒歌 (北朝民歌) 敕勒川, 陰山下。 天似穹廬, 籠蓋四野。 天蒼蒼,野茫茫, 風吹草低見牛羊。 【助讀】 川...
    干國祥備課老干閱讀 2,121評論 1 13
  • 1 “你個鱉孫兒”洪濤和部長開著玩笑,“咋又沒有荊芥類”。每次我們幾個同學小聚都選這家家鄉菜。一來家鄉菜在深圳可選...
    張前進閱讀 5,188評論 4 6
  • 今天我和許涵樂去順峰山公園跑步。我們先走了一會,然后我才跑,我們跑到一半時,發現許涵樂沒有跟上來。然后我就往...
    王者榮耀大神閱讀 822評論 0 2
  • 不管多累多苦,我都做不到放下所有,來一場說走就走的旅行。也許是牽絆太多,也許是不能狠心,所以只好學會自我安慰,學會...
    珠海紅葉原創閱讀 132評論 0 1