UIAlertView is Not Working in Swift

寵の児 提交于 2019-11-28 09:32:19

From Xcode 6.0 UIAlertView class:

UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.

On swift ( iOS 8 and OS X 10.10 ), you can do this:

var alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:handleCancel))
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in
                println("User click Ok button")
            }))
        self.presentViewController(alert, animated: true, completion: nil)

func handleCancel(alertView: UIAlertAction!)
        {
            println("User click cancel button")
        }

If you want to use in 'ActionSheet' instead 'Alert' you need only to change the UIAlertControllerStyle for example:

var alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.ActionSheet)

UIAlertView is deprecated in iOS 8, But Swift supports iOS7 and you can not use UIAlertController on iOS 7. Add the following method to solve the issue :

func showAlert(title:NSString, message:NSString,owner:UIViewController) {
    if let gotModernAlert: AnyClass = NSClassFromString("UIAlertController") {
        var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        owner.presentViewController(alert, animated: true, completion: nil)
    }
    else {
        let alertView = UIAlertView(title: title, message: message, delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
        alertView.alertViewStyle = .Default
        alertView.show()
    }
}

and call the method anywhere from the code like this :

showAlert(APP_NAME,message: "Add your alert message here" ,owner: self)

the best way for me is...

class ViewController: UIViewController, UIAlertViewDelegate {
var allarme = UIAlertView(title: "Warning", message: "This is a best way to create a alarm message", delegate: self, cancelButtonTitle: "OK")
        allarme.show()

remember to import on the class UIAlertViewDelegate

Use following way :

var altMessage = UIAlertController(title: "Warning", message: "This is Alert Message", preferredStyle: UIAlertControllerStyle.Alert)
altMessage.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(altMessage, animated: true, completion: nil)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!