// UIAlertView的自定义类
//MARK:- MODULES
import Foundation
import UIKit
//MARK:- CLASS
class Alert : NSObject{
static let shared = Alert()
var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?
/** show */
public func show(title : String?, message : String?, viewController : UIViewController?, okAction : AlertSuccess = nil) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil);
}
}
/** showWithCancelAndOk */
public func showWithCancelAndOk(title : String, okTitle : String, cancelTitle : String, message : String, viewController : UIViewController?, okAction : AlertSuccess = nil, cancelAction : AlertSuccess = nil) {
let version:NSString = UIDevice.current.systemVersion as NSString;
if version.doubleValue >= 8 {
alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
alert?.addAction(UIAlertAction(title: cancelTitle, style: .default, handler: { (action: UIAlertAction) in
if let cancelAction = cancelAction {
cancelAction()
}
}))
alert?.addAction(UIAlertAction(title: okTitle, style: .default, handler: { (action: UIAlertAction) in
if let okAction = okAction {
okAction()
}
}))
viewController?.present(alert!, animated:true, completion:nil);
}
}
/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {
let version : NSString = UIDevice.current.systemVersion as NSString
if version.doubleValue >= 8 {
alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when){
self.alert?.dismiss(animated: true, completion: nil)
}
}
}
}
使用:
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self) //without ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}) // with ok action
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
//ok action
}, cancelAction: {
//cancel action
}) //with cancel and ok action
Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self) //with timer