ios - 当从弹出窗口中选择特定操作时,将 segue 添加到另一个视图控制器
问题描述
我正在尝试链接一个特定的视图控制器,该视图控制器将在用户从选择随机数后自动生成的不同弹出窗口中选择“是”时运行。
仅当用户选择是时,我将如何添加第二个视图控制器(并在用户选择否时丢弃弹出窗口)?
我已经在 Stack 上进行了研究,有人建议使用 Storyboard 和 Segues,所以我使用“Show Segue to Weapon Pop Up View Controller”连接了第一个和第二个视图控制器,第二个 VC 的故事板 ID 为“PopUp”。
谢谢你的帮助!
这是我的代码:
@IBAction func rolld20(_ sender: Any) {
let randomnumber20 = Int.random(in: 1...20)
d20label.text = String(randomnumber20)
//create the alert
let d20alert = UIAlertController(title: "You rolled a D20!",
message: "You rolled a \(String(randomnumber20))! Is this enough?", preferredStyle: UIAlertController.Style.alert)
// add the actions (yes/no buttons)
d20alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil)) {
//code to open up second view controller with the storyboard ID "PopUp" goes here I believe?
}
d20alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: nil))
// show the alert when the user clicks to roll d20
self.present(d20alert, animated: true, completion: nil)
}
解决方案
您需要实施performSegueWithIdentifier
.
在您的情况下,代码将类似于:
@IBAction func rolld20(_ sender: Any) {
let randomnumber20 = Int.random(in: 1...20)
let d20alert = UIAlertController(title: "You rolled a D20!",
message: "You rolled a \(String(randomnumber20))! Is this enough?", preferredStyle: UIAlertController.Style.alert)
d20alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
self.performSegue(withIdentifier: "PopUp", sender: nil)
}))
d20alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: nil))
self.present(d20alert, animated: true, completion: nil)
}
为了便于阅读,我删除了评论。请记住,identifier
方法中的字符串与 SEGUE 标识符相关,而不是目标视图控制器标识符。要设置您的 segue 标识符,只需单击 segue:
并在“显示属性检查器”项上编辑标识符:
推荐阅读
- html - WordPress垂直菜单悬停效果定位
- delphi - 如何在delphi的access数据库中以一对多的关系将记录添加到两个表中
- java - 等待 SingleThreadExecutor 在继续 UI 线程执行之前将结果传递给 UI 线程 (RunOnUIThread)。安卓
- android - Can't import Android library
- javascript - Meteor.js doesn't load content of lib folder
- java - How to print 5 random colors from an array of colors
- docker - edgelet_utils... 获取 https://warlibregistry.azurecr.io/v2/iot-edge-engine-simulator/manifests/0.0.1-amd64:未授权:需要身份验证
- python - How to iterate over JSON array?
- c# - How to change the http status code after starting writing to the HttpContext.Response.Body stream in ASP.NET Core?
- wordpress - CF7:如果提交错误,重定向到另一个 URL