利用协议扩展封装UIAlertView

原创文章转载请注明出处

利用协议扩展封装UIAlertView_第1张图片
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
                })

我是咕咕鸡,一个还在不停学习的全栈工程师。
热爱生活,喜欢跑步,家庭是我不断向前进步的动力。

你可能感兴趣的:(利用协议扩展封装UIAlertView)