HTML5   发布时间:2022-04-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 如何将更多参数传递给UIAlertAction的处理程序?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法将数组“lisTineed”传递给处理函数“handleConfirmPressed”?我能够通过将其添加类变量来实现这一点,但这似乎非常hacky,现在我想为多个变量执行此操作,因此我需要更好的解决方案.

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",handler: nil))
    alert.addAction(UIAlertAction(title: "Confirm",handler:{ action in
        // whatever else you need to do here
        print(lisTineed)
    }))
    presentViewController(alert,completion: nil)
}

如果您真的想要隔离例程的功能部分,您可以随时放置:

handleConfirmPressedAction(action:action,needed:lisTineed)

进入回调块

稍微更模糊的语法,在将函数传递给完成例程和回调函数本身时都会保留函数的感觉,将handleConfirmPressed定义为curried函数

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

然后你可以使用addAction:

alert.addAction(UIAlertAction(title: "Confirm",handler: handleConfirmPressed(lisTineed)))

请注意,curried函数是以下的简写:

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

大佬总结

以上是大佬教程为你收集整理的ios – 如何将更多参数传递给UIAlertAction的处理程序?全部内容,希望文章能够帮你解决ios – 如何将更多参数传递给UIAlertAction的处理程序?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。