【问题标题】:How do I pass more parameters to a UIAlertAction's handler?如何将更多参数传递给 UIAlertAction 的处理程序?
【发布时间】:2016-01-26 02:05:27
【问题描述】:

有没有办法将数组“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
}

【问题讨论】:

  • 您也可以编写一个方法来返回您的listNeed 对象并使用该方法。
  • @Zhang 我看不出这与将其分配给类变量有什么不同

标签: ios swift uialertcontroller uialertaction


【解决方案1】:

最简单的方法是将闭包传递给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 定义为柯里化函数:

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

然后你可以addAction 使用:

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

请注意,柯里化函数是以下的简写:

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

【讨论】:

  • 但是我该如何改变这一行:alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler: handleConfirmPressed))?
  • 就像我给出的示例代码一样。如果您不熟悉 Swift 及其闭包/块语法,请翻出 Apple Swift 书籍并仔细阅读。
  • 啊,我明白你的意思了。我希望我不必使用闭包,我可以传入一个方法,但这种方法效果很好。谢谢!
  • 在 swfit 4 中应该是 func handleConfirmPressed(listINeed:[String]) -> (_ alertAction:UIAlertAction) -> () { return { alertAction in print("listINeed: (listINeed)") } }
猜你喜欢
  • 2020-04-06
  • 2014-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 2015-05-19
  • 2012-08-30
相关资源
最近更新 更多