我不断收到此错误"UIAlertView"在iOS 9.0中已弃用"



不断收到此错误:

"UIAlertView"在iOS 9.0中已弃用:UIAlertView已弃用。将 UIAlertController 与 UIAlertControllerStyleAlert 的 preferredStyle

一起使用

有人可以帮我编辑此代码吗?

if #available(iOS 8.0, *) {
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)

alert.addAction(UIAlertAction(title: alertOKTitle, style:.destructive, handler: { alertAction in
self.okButtonPressed()
alert.dismiss(animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: alertCancelTitle, style:.cancel, handler:{ alertAction in
self.cancelButtonPressed()
alert.dismiss(animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: alertRemindLaterTitle, style:.default, handler: { alertAction in
self.remindLaterButtonPressed()
alert.dismiss(animated: true, completion: nil)
}))
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let controller = appDelegate.window?.rootViewController
controller?.present(alert, animated: true, completion: nil)
} else {
let alert = UIAlertView()
alert.title = alertTitle
alert.message = alertMessage
alert.addButton(withTitle: alertCancelTitle)
alert.addButton(withTitle: alertRemindLaterTitle)
alert.addButton(withTitle: alertOKTitle)
alert.delegate = self
alert.show()
}

}
internal func alertView(_ alertView: UIAlertView , clickedButtonAt buttonIndex: Int){
if(buttonIndex == 0)
{
cancelButtonPressed()
}
else if(buttonIndex == 1)
{
remindLaterButtonPressed()
}
else if(buttonIndex == 2)
{
okButtonPressed()
}
alertView.dismiss(withClickedButtonIndex: buttonIndex, animated: true)
}

正如错误所述,UIAlertView从 iOS 9.0 开始被弃用。UIAlertController是在 iOS 8.0 中添加的。您的代码正确选择在 iOS 8.0 或更高版本下使用UIAlertController

问题是您的代码尝试将UIAlertView用于iOS 8.0之前的任何内容。但应用的部署目标未针对 iOS 7 或更早版本设置。因此,编译器告诉您UIAlertView已被弃用。

由于您实际上不会支持iOS 8.0之前的任何内容,因此不需要if #available(iOS 8.0, *)UIAlertView。只需使用UIAlertController编写代码,而不必担心UIAlertView

您发布的所有代码都可以简化为UIAlertController部分:

let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: alertOKTitle, style:.destructive, handler: { alertAction in
self.okButtonPressed()
alert.dismiss(animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: alertCancelTitle, style:.cancel, handler:{ alertAction in
self.cancelButtonPressed()
alert.dismiss(animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: alertRemindLaterTitle, style:.default, handler: { alertAction in
self.remindLaterButtonPressed()
alert.dismiss(animated: true, completion: nil)
}))
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let controller = appDelegate.window?.rootViewController
controller?.present(alert, animated: true, completion: nil)

最新更新