gpt4 book ai didi

ios - 如何将更多参数传递给 UIAlertAction 的处理程序?

转载 作者:搜寻专家 更新时间:2023-10-30 22:24:39 25 4
gpt4 key购买 nike

有没有办法将数组“listINeed”传递给处理函数“handleConfirmPressed”?我可以通过将它添加为类变量来做到这一点,但这看起来很老套,现在我想对多个变量这样做,所以我需要一个更好的解决方案。

func someFunc(){
//some stuff...
let listINeed = [someObject]

let alert = UIAlertController(title: "Are you sure?", message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler: handleConfirmPressed))
presentViewController(alert, animated: true, completion: nil)
}

func handleConfirmPressed(action: UIAlertAction){
//need listINeed here
}

最佳答案

最简单的方法是将闭包传递给 UIAlertAction 构造函数:

func someFunc(){
//some stuff...
let listINeed = [ "myString" ]

let alert = UIAlertController(title: "Are you sure?", message: "message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler:{ action in
// whatever else you need to do here
print(listINeed)
}))
presentViewController(alert, animated: true, completion: nil)
}

如果你真的想隔离例程的功能部分,你总是可以放:

handleConfirmPressedAction(action:action, needed:listINeed)

进入回调 block

一个稍微晦涩的语法,在将它传递给完成例程和在回调函数本身中保留函数的感觉是将 handleConfirmPressed 定义为柯里化(Currying)函数:

func handleConfirmPressed(listINeed:[String])(alertAction:UIAlertAction) -> (){
print("listINeed: \(listINeed)")
}

然后你可以addAction使用:

alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler: handleConfirmPressed(listINeed)))

请注意,柯里化(Currying)函数是以下内容的简写:

func handleConfirmPressed(listINeed:[String]) -> (alertAction:UIAlertAction) -> () {
return { alertAction in
print("listINeed: \(listINeed)")
}
}

关于ios - 如何将更多参数传递给 UIAlertAction 的处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35005922/

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