我一直在尝试从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' ...]
}
由于代码很长,我无法将代码放入警报动作中,并且它也可以在其他进程中运行。
答案 0 :(得分:1)
我无法将代码放入警报动作中
是的,您可以,这是您必须要做的。动作 是您发出警报已被取消的信号(它还告诉您警报中点击了哪个按钮)。您不必将代码本身放入操作中;您只需要调用该代码即可。
示例:
alert.addAction(UIAlertAction(title: "Boy", style: .default, handler: { action in
self.myVeryLongFunction(genre:"Boy")
}))
答案 1 :(得分:0)
警报无法按您期望的那样工作,它假设询问用户并等待其操作,因此它是异步的
var genre = "Boy" // default
func showPopUp(name:String) {
let alert = UIAlertController(title: "What are you "+name+"?", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Boy", style: .default, handler: { action in
self.genre = "Boy"
self.handleSelection()
}))
alert.addAction(UIAlertAction(title: "Girl", style: .default, handler: { action in
self.genre = "Girl"
self.handleSelection()
}))
self.present(alert, animated: true)
}
func handleSelection() {
print("current selected genre is \(genre)")
}
加上这个
showPopUp(name: "John")
应该放在viewDidAppear
内,因为现在viewDidLoad
内显示vc的视图尚未完全放置
var once = true
override func viewDidAppear(_ animated:Bool) {
super.viewDidAppear(animated)
if once {
showPopUp(name: "John")
once = false // to prevent re-showing it again
}
}
答案 2 :(得分:0)
创建一个单独的函数,然后从完成处理程序中对其进行调用。
像这样
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"
self.afterPopup()
}))
alert.addAction(UIAlertAction(title: "Girl", style: .default, handler: { action in
genre = "Girl"
self.afterPopup()
}))
self.present(alert, animated: true)
return genre
}
override func viewDidLoad() {
super.viewDidLoad()
print("This should appear before the alert")
let a = showPopUp(name: "John)
}
func afterPopup(){
print("This should appear after the response")
print("John is a "+a)
[...more code using variable 'a' ...]
}
此外,请注意在ViewDidLoad中显示弹出窗口。如果显示此视图,则会引发警告(并可能导致应用奇怪的行为)