如何在Swift Playgrounds中获得弹出对话框

问题描述 投票:0回答:1

我想知道如何在Swift Playgrounds中弹出一个对话框(是的,必须在Playgrounds中)我尝试了以下代码(直接来自AppleDevs网站)

但是,无论我尝试什么,self标签总是会抛出错误。谁能帮我这个?

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)
swift swift-playground
1个回答
2
投票

需要从视图控制器呈现警报。而不是意味着它将出现在助理编辑器内的模拟器中:

例:

import UIKit
import PlaygroundSupport

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.")
}))
let v = UIViewController()
PlaygroundPage.current.liveView = v
v.present(alert, animated: true, completion: nil)
© www.soinside.com 2019 - 2024. All rights reserved.