Schrijvende handler voor UIAlertAction

Ik presenteer een UIAlertViewaan de gebruiker en ik weet niet hoe ik de handler moet schrijven. Dit is mijn poging:

let alert = UIAlertController(title: "Title",
                            message: "Message",
                     preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                            handler: {self in println("Foo")})

Ik krijg een heleboel problemen met Xcode.

De documentatie zegt convenience init(title title: String!, style style: UIAlertActionStyle, handler handler: ((UIAlertAction!) -> Void)!)

De hele blokken/sluitingen gaat me op dit moment een beetje te ver. Elke suggestie wordt zeer op prijs gesteld.


Antwoord 1, autoriteit 100%

In plaats van zelf in je handler, zet je (waarschuwing: UIAlertAction!). Dit zou je code er zo uit moeten laten zien

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

dit is de juiste manier om handlers in Swift te definiëren.

Zoals Brian hieronder aangaf, zijn er ook eenvoudigere manieren om deze handlers te definiëren. Het gebruik van zijn methoden wordt besproken in het boek, kijk naar de sectie met de titel Sluitingen


Antwoord 2, autoriteit 44%

Functies zijn eersteklas objecten in Swift. Dus als u geen sluiting wilt gebruiken, kunt u ook gewoon een functie met de juiste handtekening definiëren en deze vervolgens doorgeven als het argument handler. Let op:

func someHandler(alert: UIAlertAction!) {
    // Do something...
}
alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                              handler: someHandler))

Antwoord 3, autoriteit 11%

Je kunt het zo simpel doen met 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")
 }))

Alle antwoorden hierboven zijn correct, ik laat alleen een andere manier zien die kan worden gedaan.


Antwoord 4, autoriteit 6%

Laten we aannemen dat u een UIAlertAction met hoofdtitel, twee acties (opslaan en verwijderen) en annuleerknop wilt:

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)

Dit werkt voor swift 2 (Xcode versie 7.0 beta 3)


Antwoord 5, autoriteit 5%

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)

Antwoord 6, autoriteit 4%

Syntaxiswijziging in swift 3.0

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

Antwoord 7, autoriteit 2%

zo doe ik het met xcode 7.3.1

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

// maak de knop

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

// de knop toevoegen aan het waarschuwingsbeheer

myAlert.addAction(sayhi);

// de hele code, deze code voegt 2 knoppen toe

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

Antwoord 8, autoriteit 2%

waarschuwing maken, getest in 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)

en de functie

func finishAlert(alert: UIAlertAction!)
{
}

Antwoord 9

  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 doelstelling 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];
    

Antwoord 10

In Swift 5 kunt u ook het volgende doen:

let handler = { (action: UIAlertAction!) -> Void in
    //do tasks
}

Als je de actie aan het maken bent, vervang deze dan als volgt:

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

Other episodes