Swift 4.0封装Alert和ActionSheet
2018-09-26 本文已影响0人
biyu6
处理 取消按钮 + N个按钮 的点击事件
支持 alert 和 actionSheet 两种样式
封装代码
import UIKit
class BYAlertActionSheetTool { // 处理 取消按钮 + N个按钮 的点击事件
static func showAlert(titleStr: String?, msgStr: String?, style: UIAlertController.Style = .alert, currentVC: UIViewController, cancelBtn: String = "取消", cancelHandler:((UIAlertAction) -> Void)?, otherBtns:Array<String>?, otherHandler:((Int) -> ())?) {
//DispatchQueue.global().async{}//子线程
DispatchQueue.main.async { // 主线程执行
let alertController = UIAlertController(title: titleStr, message: msgStr,preferredStyle: style)
//取消按钮
let cancelAction = UIAlertAction(title:cancelBtn, style: .cancel, handler:{ (action) -> Void in
cancelHandler?(action)
})
alertController.addAction(cancelAction)
//其他按钮
if otherBtns != nil {
for (index, value) in (otherBtns?.enumerated())! {
let otherAction = UIAlertAction(title: value, style: .default, handler: { (action) in
otherHandler!(index)
})
alertController.addAction(otherAction)
}
}
currentVC.present(alertController, animated: true, completion: nil)
}
}
}
调用代码
BYAlertActionSheetTool.showAlert(titleStr: nil, msgStr: "电话号码不能为空,是否删除该联络人?", style: .actionSheet, currentVC: self, cancelBtn: "取消", cancelHandler: { (cancelAction) in
printLog(message: "点击了取消按钮")
}, otherBtns: ["拍照","相册","录像","小视频"]) { (idx) in
printLog(message: "点击了第\(idx)个按钮")
}
极简调用(默认alert样式,“取消”)
BYAlertActionSheetTool.showAlert(titleStr: nil, msgStr: "电话号码不能为空,是否删除该联络人?", currentVC: self, cancelHandler: nil, otherBtns: nil, otherHandler: nil)