从 UIAlertAction 获取 UIAlertController?

Get the UIAlertController from UIAlertAction?

我想调用函数而不是使用带有 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?
}

你能试试下面的代码吗:

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 中得到一个 TextField。可能下面的代码会对你有所帮助。

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)
    }
}

希望对您有所帮助!

一个操作没有引用它包含的警报。尽管如此,这只是一个提前计划的问题。如果您需要 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住在别的地方,你可以做到。

我最后做的是创建一个新的 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