今天要來客製化我們的alert,一呼叫alert的方式為:
let alert = UIAlertController(title: "這是alert", message: "你的訊息", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "確定", style: .default, handler: { (_) in
}))
self.present(alert, animated: true, completion: {
print("completion block")
})
class TAlertView: NSObject{
class func showAlertWith(title: String?, message: String?, setCancelTitle: String?, setConfirmTitle: String?, delegate: UIViewController, completion: (() -> Void)?, cancel: (() -> Void)?){
DispatchQueue.main.async {
let message = message ?? ""
let title = title ?? ""
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
let confirmAction = UIAlertAction(title: setConfirmTitle, style: .default) { (UIAlertAction) -> Void in
completion?()
}
let cancelAction = UIAlertAction(title: setCancelTitle, style: .cancel) { (UIAlertAction) -> Void in
cancel?()
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
delegate.present(alertController, animated: true, completion: nil)
}
}
}
這樣就可以在別的vc呼叫到了,然後你就可以自訂你要的內容,可以讓程式碼更簡潔一點~
這裡也有用到我們之前的閉包,你要做的事情都可以寫進去~