简体   繁体   中英

Why doesn't this UIAlertController show?

While attempting to implement a UI Alert I have encountered some issues. I am using swift 3.0 in Xcode 8 beta 4, I am attempting to have a button which activates a alert, one button (cancel) dismisses the alert the other (ok) performs an action as a UIAction Button would, however I have been unable to even get an alert to show.

var warning = UIAlertController(title: "warning", message: "This will erase all content", preferredStyle: .Alert)

var okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
    UIAlertAction in
    NSLog("OK Pressed")
}

var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
    UIAlertAction in
    NSLog("Cancel Pressed")
}

warning.addAction(okAction) {
   // this is where the actions to erase the content in the strings 
}
warning.addAction(cancelAction)

self.presentViewController(warning, animated: true, completion: nil)

That code isn't compatible with Swift 3. Things like .Alert are now .alert . And the presentViewController method is quite different.

This should work.

let warning = UIAlertController(title: "warning", message: "This will erase all content", preferredStyle: .alert)

    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
        UIAlertAction in
        NSLog("OK Pressed")
        //ok action should go here
    }


    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
        UIAlertAction in
        NSLog("Cancel Pressed")
    }

    warning.addAction(okAction)
    warning.addAction(cancelAction)

    present(warning, animated: true, completion: nil)

Why did you have the closure after addAction(okAction) instead of when you created the alert?

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM