swift - 暂停代码,直到在 Swift 中获得 UIAlertController 的响应
问题描述
我一直试图从 UIAlertController 的用户那里得到答案。问题是在显示 UIAlertController 时代码仍在运行。我想显示警报,然后等到用户给出答案以继续代码。
func showPopUp(name:String)->String{
var genre = ""
let alert = UIAlertController(title: "What are you "+name+"?", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Boy", style: .default, handler: { action in
genre = "Boy"
}))
alert.addAction(UIAlertAction(title: "Girl", style: .default, handler: { action in
genre = "Girl"
}))
self.present(alert, animated: true)
return genre
}
override func viewDidLoad() {
super.viewDidLoad()
print("This should appear before the alert")
let a = showPopUp(name: "John)
print("This should appear after the response")
print("John is a "+a)
[...more code using variable 'a' ...]
}
我不能将代码放在警报的操作中,因为它很长,而且它也在其他进程中运行。
解决方案
我无法将代码放入警报的操作中
是的,你可以,这是你必须做的。该操作是您发出警报已被解除的信号(它还告诉您在警报中点击了哪个按钮)。您不必将代码本身放入操作中;您只需要调用该代码即可。
例子:
alert.addAction(UIAlertAction(title: "Boy", style: .default, handler: { action in
self.myVeryLongFunction(genre:"Boy")
}))
推荐阅读
- spring - Thymeleaf 布局方言“模板解析期间发生错误”
- python - python中二维数组中2点之间的距离
- java - 如何纠正我在迭代产品数组列表时的错误?
- angular - 微前端路由:Web 组件/角度元素中的角度路由器
- django - 获取请求参数不触发Django中的if语句
- python - 在 PyQtGraph 上放大/缩小时从 PyQt 更新滑块
- javascript - 如何更改chrome默认副本号
- python - 如何定义起始位置和结束位置,然后告诉海龟连接它们
- java - 如何为 ListAdapter 实现方法 getFilter
- c++ - 错误:C++ 中“]”标记之前的预期主表达式