开发中不免要经常弹框提醒,如果在每个要提醒的 ViewController 中写 UIAlertController 弹框逻辑,那重复代码就太多了。鉴于此,我们把 UIAlertController 弹框事件封装到工具类。在需要弹框的页面,直接调用工具类方法就行了。这样可以清洁代码。达到 less code do more things 的效果。
下面是工具类方法:
import Foundation
import UIKit
struct MFAlertAction {
static let internetAlertTitle = "网络连接失败"
static let internetAlertMessage = "网络连接失败,请重试!"
private static func showAlert(on vc:UIViewController,with title:String, message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
DispatchQueue.main.async {
vc.present(alert, animated: true, completion: nil)
}
}
// Show Alert like internet failure
static func showInternetFailureAlert(on vc:UIViewController){
showAlert(on: vc, with: internetAlertTitle, message: internetAlertMessage)
}
// Show Common Alerts
static func showCommonAlert(on vc:UIViewController,title:String,message:String){
showAlert(on: vc, with: title, message: message)
}
}
在需要用到的地方,直接调用就行。如:
MFAlertAction.showCommonAlert(on: self,title: "提示",message: "出现错误,请重试")
MFAlertAction.showInternetFailureAlert(on: self)
网友评论