问题
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)
回答1:
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)
来源:https://stackoverflow.com/questions/55127152/how-do-i-get-a-popup-dialog-box-in-swift-playgrounds