Writing handler for UIAlertAction

后端 未结 9 842
北恋
北恋 2020-11-28 05:10

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

let alert = UIAlertController(ti         


        
相关标签:
9条回答
  • 2020-11-28 05:38

    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 handler argument. Observe:

    func someHandler(alert: UIAlertAction!) {
        // Do something...
    }
    
    alert.addAction(UIAlertAction(title: "Okay",
                                  style: UIAlertActionStyle.Default,
                                  handler: someHandler))
    
    0 讨论(0)
  • 2020-11-28 05:39

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

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

    this is the proper way to define handlers in 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

    0 讨论(0)
  • 2020-11-28 05:40

    In 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)
    
    0 讨论(0)
提交回复
热议问题