1

是否可以将函数连接到UIAlertAction?

那么在用户单击“确定”按钮后,它会执行一个操作吗?这不是 handler 参数的作用吗?

let alert: UIAlertController = UIAlertController(title: "Email already registered", message: "Please enter a different email", preferredStyle: .alert)
let okButton = UIAlertAction(title: "OK", style: .default, handler: backToLogin())

alert.addAction(okButton)
self.presentViewController(alert, animated: true, completion: nil)

...

func backToLogin() {
    self.performSegueWithIdentifier("toLoginPage", sender: self)
}
4

2 回答 2

4

您可以将函数用作handler,但它需要具有正确的类型。handler: backToLogin()此外,当您将它作为参数传递时,您也不能调用它,即,backToLogin如果handler: backToLogin没有().

以下应该有效:

func backToLogin(alertAction: UIAlertAction) {
    self.performSegueWithIdentifier("toLoginPage", sender: self)
}
let okButton = UIAlertAction(title: "OK", style: .Default, handler: backToLogin)

但是不得不改变backToLogin可能会破坏目的,所以你可以只使用一个闭包:

let okButton = UIAlertAction(title: "OK", style: .Default) { _ in
    self.backToLogin()
}
于 2015-07-24T04:04:21.930 回答
0
You need to enter the handler

let okButton = UIAlertAction(title: "OK", style: .Default, handler: {

(UIAlertAction) in

self.backToLogin()

})

}

有关更多信息,请参阅此答案:为 UIAlertAction 编写处理程序

于 2015-07-24T03:25:20.033 回答