我一直试图从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")
}))
创建一个单独的函数,并从完成处理程序中为您的操作调用它。
像这样
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中显示弹出窗口。如果正在显示此视图,则会发出警告(并可能导致app的奇怪行为)
警报不会像您期望的那样工作,它假设要求用户并等待他的操作,因此它是异步的
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
}
}