本文介绍了如何在 Swift Playgrounds 中获得弹出对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

然而,无论我尝试什么,self 标签总是 会抛出错误.有人能帮我解决这个问题吗?

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)

推荐答案

警报需要从视图控制器呈现.这意味着它会出现在助手编辑器内的模拟器中:

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

示例:

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)

这篇关于如何在 Swift Playgrounds 中获得弹出对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 10:54