2

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)
James Webster
  • 31,873
  • 11
  • 70
  • 114
Yellow
  • 175
  • 1
  • 15

1 Answers1

3

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!

D. Greg
  • 991
  • 1
  • 9
  • 21
  • Thank you so much ill give it a try when I get home, its a shame there isnt much help out there for swift3.0 yet. Greatly appriecated. – Yellow Aug 18 '16 at 03:44