原創文章轉載請注明出處
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
})
我是咕咕雞,一個還在不停學習的全棧工程師。
熱愛生活,喜歡跑步,家庭是我不斷向前進步的動力。