我想调用一个函数,而不是对一个UIAlertAction使用闭包。是否有可能获得对拥有UIAlertController的UIAlertAction的引用?
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?
}发布于 2015-10-06 05:17:33
操作不引用其包含的警报。不过,这只是提前计划的问题。如果需要okAlert来对警报控制器进行引用,那么给它这个引用:
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住在其他地方,你可以这样做。
发布于 2015-10-05 02:49:45
你能试试下面的代码吗?
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")
})
}我不知道你到底想要什么。但我认为你想在UIAlertController里面装一个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)
}
}希望这能帮上忙!
发布于 2017-10-27 19:27:29
最后我要做的是创建一个新的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 = alertControllerhttps://stackoverflow.com/questions/32940361
复制相似问题