我正在向用户呈现一个UIAlertView
,但我不知道如何编写处理程序。这是我的尝试:
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)!)
目前整个代码块/闭包都有点让我摸不着头脑。任何建议都是非常感谢的。
发布于 2014-06-13 01:25:33
在处理程序中放入(警告: UIAlertAction!),而不是self。这将使您的代码看起来如下所示
alert.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: {(alert: UIAlertAction!) in println("Foo")}))
这是在Swift中定义处理程序的正确方式。
正如Brian在下面指出的,还有更简单的方法来定义这些处理程序。书中讨论了如何使用他的方法,请看标题为闭包的一节
发布于 2015-03-15 05:27:24
函数是Swift中的一级对象。因此,如果您不想使用闭包,也可以只定义一个具有适当签名的函数,然后将其作为handler
参数传递。请注意:
func someHandler(alert: UIAlertAction!) {
// Do something...
}
alert.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: someHandler))
发布于 2016-02-08 22:45:50
你可以使用swift 2这样简单地完成:
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")
}))
上面所有的答案都是正确的,我只是展示了另一种可以做到的方法。
https://stackoverflow.com/questions/24190277
复制相似问题