首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >正在为UIAlertAction编写处理程序

正在为UIAlertAction编写处理程序
EN

Stack Overflow用户
提问于 2014-06-13 01:17:30
回答 8查看 121.2K关注 0票数 108

我正在向用户呈现一个UIAlertView,但我不知道如何编写处理程序。这是我的尝试:

代码语言:javascript
复制
let alert = UIAlertController(title: "Title",
                            message: "Message",
                     preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                            handler: {self in println("Foo")})

我在Xcode中遇到了一堆问题。

文档上写着convenience init(title title: String!, style style: UIAlertActionStyle, handler handler: ((UIAlertAction!) -> Void)!)

目前整个代码块/闭包都有点让我摸不着头脑。任何建议都是非常感谢的。

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2014-06-13 01:25:33

在处理程序中放入(警告: UIAlertAction!),而不是self。这将使您的代码看起来如下所示

代码语言:javascript
复制
    alert.addAction(UIAlertAction(title: "Okay",
                          style: UIAlertActionStyle.Default,
                        handler: {(alert: UIAlertAction!) in println("Foo")}))

这是在Swift中定义处理程序的正确方式。

正如Brian在下面指出的,还有更简单的方法来定义这些处理程序。书中讨论了如何使用他的方法,请看标题为闭包的一节

票数 170
EN

Stack Overflow用户

发布于 2015-03-15 05:27:24

函数是Swift中的一级对象。因此,如果您不想使用闭包,也可以只定义一个具有适当签名的函数,然后将其作为handler参数传递。请注意:

代码语言:javascript
复制
func someHandler(alert: UIAlertAction!) {
    // Do something...
}

alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                              handler: someHandler))
票数 76
EN

Stack Overflow用户

发布于 2016-02-08 22:45:50

你可以使用swift 2这样简单地完成:

代码语言:javascript
复制
let alertController = UIAlertController(title: "iOScreator", message:
        "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
        self.pressed()
}))

func pressed()
{
    print("you pressed")
}

    **or**


let alertController = UIAlertController(title: "iOScreator", message:
        "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
      print("pressed")
 }))

上面所有的答案都是正确的,我只是展示了另一种可以做到的方法。

票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24190277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档