ios 为 UIAlertAction 编写处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24190277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:52:10  来源:igfitidea点击:

Writing handler for UIAlertAction

iosuialertviewswiftuialertcontroller

提问by Steve Marshall

I'm presenting a UIAlertViewto the user and I can't figure out how to write the handler. This is my attempt:

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

let alert = UIAlertController(title: "Title",
                            message: "Message",
                     preferredStyle: UIAlertControllerStyle.Alert)

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

I get a bunch of issues in Xcode.

我在 Xcode 中遇到了很多问题。

The documentation says convenience init(title title: String!, style style: UIAlertActionStyle, handler handler: ((UIAlertAction!) -> Void)!)

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

The whole blocks/closures is a little over my head at the moment. Any suggestion are much appreciated.

目前,整个街区/闭包有点超出我的想象。任何建议都非常感谢。

回答by jbman223

Instead of self in your handler, put (alert: UIAlertAction!). This should make your code look like this

而不是 self 在您的处理程序中,放置(警报:UIAlertAction!)。这应该使您的代码看起来像这样

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

this is the proper way to define handlers in Swift.

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

As Brian pointed out below, there are also easier ways to define these handlers. Using his methods is discussed in the book, look at the section titled Closures

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

回答by Rob Johansen

Functions are first-class objects in Swift. So if you don't want to use a closure, you can also just define a function with the appropriate signature and then pass it as the handlerargument. Observe:

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

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

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

回答by Korpel

You can do it as simple as this using swift 2:

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

All the answers above are correct i am just showing another way that can be done.

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

回答by polarware

Lets assume that you want an UIAlertAction with main title, two actions (save and discard) and cancel button:

让我们假设您想要一个带有主标题、两个操作(保存和丢弃)和取消按钮的 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)

This works for swift 2 (Xcode Version 7.0 beta 3)

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

回答by Fangming

Syntax change in swift 3.0

swift 3.0 中的语法更改

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

回答by mohamad taghadosi

In Swift 4 :

在 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)

回答by luhuiya

create alert, tested in xcode 9

创建警报,在 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)

and the function

和功能

func finishAlert(alert: UIAlertAction!)
{
}

回答by Alan

this is how i do it with xcode 7.3.1

这就是我如何使用 xcode 7.3.1

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

// create the button

// 创建按钮

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

// adding the button to the alert control

// 将按钮添加到警报控件

myAlert.addAction(sayhi);

// the whole code, this code will add 2 buttons

// 整个代码,这段代码会添加2个按钮

  @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")
    }

回答by Silversky Technology

  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];
    
  1. 在斯威夫特

    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. 在目标 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];