gpt4 book ai didi

swift - UIAlertAction 可以触发函数吗?

转载 作者:搜寻专家 更新时间:2023-11-01 06:44:48 29 4
gpt4 key购买 nike

是否可以将函数连接到 UIAlertAction

那么在用户点击 OK 按钮后它会执行一个操作吗?这不是 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)
}

最佳答案

您可以使用函数作为 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()
}

关于swift - UIAlertAction 可以触发函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31601577/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com