编写用于UIAlertAction的处理程序

114

我正在向用户展示一个 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)!)

目前对闭包还不是很了解,有什么建议将不胜感激。

10个回答

173

将您的处理程序中的 self 替换为 (alert: UIAlertAction!)。这样做应该使您的代码看起来像这样

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

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

如Brian在下面指出的,还有更简单的方法来定义这些处理程序。使用他的方法在书中进行了讨论,请查看标题为Closures的部分。


9
{alert in println("Foo")}, {_ in println("Foo")}, 和 {println("Foo")} 应该也可以工作。 (注:这是Swift中的一些闭包表达式,它们都可以用来执行打印 "Foo" 的操作。第一个闭包使用了参数名 alert,但没有使用该参数;第二个闭包使用下划线 _ 表示未使用的参数;第三个闭包没有任何参数。) - Brian Nickel
8
第三个不起作用是因为你需要处理参数操作。但除此之外,在Swift中你不需要编写UIAlertActionStyle.Default,.Default也可以使用。 - Ben
请注意,如果您使用“let foo = UIAlertAction(...)”,那么您可以使用尾随闭包语法将可能是长闭包放在UIAlertAction之后 - 这样看起来非常好。 - David H
1
以下是一种优雅的编写方式:alert.addAction(UIAlertAction(title: "确定", style: .default) { _ in println("Foo") }) - Elijah

81

在Swift中,函数是一等公民。因此,如果您不想使用闭包,您也可以定义一个具有适当签名的函数,然后将其作为handler参数传递。例如:

func someHandler(alert: UIAlertAction!) {
    // Do something...
}

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

这个 Objective-C 的处理函数应该长什么样子? - andilabs
1
在 Swift 中,函数是闭包,我觉得这很酷。请查看文档:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html - kakubei

19
你可以使用 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")
 }))

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


11

假设您想要一个具有主标题、两个操作(保存和放弃)和取消按钮的UIAlertAction:

let actionSheetController = UIAlertController (title: "My Action Title", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)

    //Add Cancel-Action
    actionSheetController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))

    //Add Save-Action
    actionSheetController.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
        print("handle Save action...")
    }))

    //Add Discard-Action
    actionSheetController.addAction(UIAlertAction(title: "Discard", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
        print("handle Discard action ...")
    }))

    //present actionSheetController
    presentViewController(actionSheetController, animated: true, completion: nil)

这适用于Swift 2(Xcode版本7.0 beta 3)


9
在 Swift 4 中:
let alert=UIAlertController(title:"someAlert", message: "someMessage", preferredStyle:UIAlertControllerStyle.alert )

alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: {
        _ in print("FOO ")
}))

present(alert, animated: true, completion: nil)

7

Swift 3.0中语法的变化

alert.addAction(UIAlertAction(title: "Okay",
                style: .default,
                handler: { _ in print("Foo") } ))

4

在Xcode 9中创建警告

let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: self.finishAlert))
self.present(alert, animated: true, completion: nil)

并且这个功能

func finishAlert(alert: UIAlertAction!)
{
}

4

以下是我如何使用Xcode 7.3.1进行操作的步骤:

// create function
func sayhi(){
  print("hello")
}

// 创建按钮

let sayinghi = UIAlertAction(title: "More", style: UIAlertActionStyle.Default, handler:  { action in
            self.sayhi()})

// 将按钮添加到警告控件中

myAlert.addAction(sayhi);

// 整个代码,这段代码将添加两个按钮
  @IBAction func sayhi(sender: AnyObject) {
        let myAlert = UIAlertController(title: "Alert", message:"sup", preferredStyle: UIAlertControllerStyle.Alert);
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)

        let sayhi = UIAlertAction(title: "say hi", style: UIAlertActionStyle.Default, handler:  { action in
            self.sayhi()})

        // this action can add to more button
        myAlert.addAction(okAction);
        myAlert.addAction(sayhi);

        self.presentViewController(myAlert, animated: true, completion: nil)
    }

    func sayhi(){
        // move to tabbarcontroller
     print("hello")
    }

1
  1. In Swift

    let alertController = UIAlertController(title:"Title", message: "Message", preferredStyle:.alert)
    
    let Action = UIAlertAction.init(title: "Ok", style: .default) { (UIAlertAction) in
        // Write Your code Here
    }
    
    alertController.addAction(Action)
    self.present(alertController, animated: true, completion: nil)
    
  2. In Objective C

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *OK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
    {
    }];
    
    [alertController addAction:OK];
    
    [self presentViewController:alertController animated:YES completion:nil];
    

0
在Swift 5中,您还可以做以下操作:
let handler = { (action: UIAlertAction!) -> Void in
    //do tasks
}

然后当你执行操作时,只需像这样替换它:

let action = UIAlertAction(title: "Do it", style: .default, handler: handler)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接