// UIAlertView的自定义类
import Foundation
import UIKit
class Alert : NSObject{
static let shared = Alert()
var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?
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);
}
}
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);
}
}
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)
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
})
Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
}, cancelAction: {
})
Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self)
self
所属的类采用了协议UIAlertViewDelegate
(在Swift中,推荐的方法是使用扩展)。 - Nicolas Miari