利用协议扩展封装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,113评论 1 13
  • 1 “你个鳖孙儿”洪涛和部长开着玩笑,“咋又没有荆芥类”。每次我们几个同学小聚都选这家家乡菜。一来家乡菜在深圳可选...
    张前进阅读 5,162评论 4 6
  • 今天我和许涵乐去顺峰山公园跑步。我们先走了一会,然后我才跑,我们跑到一半时,发现许涵乐没有跟上来。然后我就往...
    王者荣耀大神阅读 820评论 0 2
  • 不管多累多苦,我都做不到放下所有,来一场说走就走的旅行。也许是牵绊太多,也许是不能狠心,所以只好学会自我安慰,学会...
    珠海红叶原创阅读 132评论 0 1