我想调用一个函数而不是使用带有UIAlertAction的闭包。是否可以获得对拥有UIAlertAction的UIAlertController的引用?
alert = UIAlertController(title: "City", message: "Enter a city name", preferredStyle: UIAlertControllerStyle.Alert)
UIAlertActionStyle.Default, handler: okAlert)
//...
func okAlert(action: UIAlertAction) {
// Get to alert here from action?
}
答案 0 :(得分:5)
操作没有引用其包含警报。不过,这只是提前规划的问题。如果您需要okAlert
来引用警报控制器,那么<em>提供它的引用:
func okAlert(_ action: UIAlertAction, _ alert:UIAlertController) {
// Get to alert here?
// yes! it is `alert`!
}
你仍然需要一个闭包来捕捉alert
并传递它:
let alert = UIAlertController(
title: "City", message: "Enter a city name", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title:"OK", style:.Default, handler: {
action in self.okAlert(action, alert)
}))
可能有详细信息要解决。但关键是,如果你想让okAlert
住在其他地方,你就可以做到。
答案 1 :(得分:0)
您可以尝试下面的代码:
let alert = UIAlertController(title: "Test alert title", message: "Test alert body", preferredStyle: .Alert)
alert.addAction(callback())
presentViewController(alert, animated: true, completion: nil)
callback
:
func callback() -> UIAlertAction {
return UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
print("alert action")
})
}
我不知道你想要什么。但我认为你想在TextField
内获得UIAlertController
。可能是下面的代码会帮助你。
var alert: UIAlertController?
let tfTag = 123
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if alert == nil {
self.alert = UIAlertController(title: "Test alert title", message: "Test alert body", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
// Get your TextField
if let tf = self.alert!.view.viewWithTag(self.tfTag) as? UITextField {
print("Value: \(tf.text)")
}
})
self.alert!.addAction(action)
// Insert UITextField
let textField = UITextField()
textField.text = "Hello World"
textField.tag = tfTag
self.alert!.view.addSubview(textField)
presentViewController(self.alert!, animated: true, completion: nil)
}
}
希望有所帮助!
答案 2 :(得分:0)
我最后做的是创建一个新的UIAlertAction子类:
public class UIAlertActionWithAlertController : UIAlertAction {
public weak var alertController: UIAlertController?
}
然后我创建动作:
let myAction = UIAlertActionWithAlertController(title: "Action", style: .default) { (action) in
if let alertController = (action as! UIAlertActionWithAlertController).alertController {
// Use alertController here
}}
并在将警报添加到警报的代码中:
alertController.addAction(myAction)
myAction.alertController = alertController