[英]How do I pass more parameters to a UIAlertAction's handler?
有沒有辦法將數組“listINeed”傳遞給處理程序 function“handleConfirmPressed”? 我能夠通過將它添加為 class 變量來做到這一點,但這看起來很老套,現在我想對多個變量這樣做,所以我需要一個更好的解決方案。
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)
進入回調塊
稍微更模糊的語法,在將函數傳遞給完成例程和回調函數本身時都會保留函數的感覺,將handleConfirmPressed
定義為curried函數:
func handleConfirmPressed(listINeed:[String])(alertAction:UIAlertAction) -> (){
print("listINeed: \(listINeed)")
}
然后你可以使用addAction
:
alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler: handleConfirmPressed(listINeed)))
請注意,curried函數是以下的簡寫:
func handleConfirmPressed(listINeed:[String]) -> (alertAction:UIAlertAction) -> () {
return { alertAction in
print("listINeed: \(listINeed)")
}
}
我認為這更容易。
class MyUIAlertAction: UIAlertAction {
var params: [String: Any] = [:]
}
func someFunc(){
//some stuff...
let listINeed = [ "myString" ]
let alert = UIAlertController(title: "Are you sure?", message: "message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
let action = MyUIAlertAction(title: "Confirm", style: .destructive, handler:{ (action: UIAlertAction) in
if let myaction = action as? MyUIAlertAction {
let listINeed = myaction.params["listINeed"] as? [String] ?? []
// whatever else you need to do here
print(listINeed)
}
})
action.params["listINeed"] = listINeed
alert.addAction(action)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.