Search code examples
swiftswift-playground

How do I get a popup dialog box in Swift Playgrounds


I was wondering how to get a dialog box to popup in Swift Playgrounds (yes must be in Playgrounds) I've tried the following code (directly from the AppleDevs site)

However, no matter what I try, the self tag always throws an error. Can anyone help me with this?

import UIKit
let alert = UIAlertController(title: "My Alert", message: "This is an alert.", preferredStyle: .alert) 
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: { _ in 
    NSLog("The \"OK\" alert occured.")
}))
self.present(alert, animated: true, completion: nil)

Solution

  • Alerts need to be presented from a view controller. than means its going to show up in the simulator inside the assistant editor:

    Example:

    import UIKit
    import PlaygroundSupport
    
    let alert = UIAlertController(title: "My Alert", message: "This is an alert.", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: { _ in
        NSLog("The \"OK\" alert occured.")
    }))
    let v = UIViewController()
    PlaygroundPage.current.liveView = v
    v.present(alert, animated: true, completion: nil)