2014-09-24 13 views
11

A UIView ha bisogno di cambiare un'etichetta di avvertimento a seconda del gestore completamento di un controllo personalizzato:chiusure nidificati non piace lista di argomenti

voucherInputView.completionHandler = {[weak self] (success: Bool) -> Void in 

     self?.proceedButton.enabled = success 
     self?.warningLabel.alpha = 1.0 

     if success 
     { 
      self?.warningLabel.text = "Code you entered is correct" 
      self?.warningLabel.backgroundColor = UIColor.greenColor() 
     } 
     else 
     { 
      self?.warningLabel.text = "Code you entered is incorrect" 
      self?.warningLabel.backgroundColor = UIColor.orangeColor() 
     } 


     UIView.animateWithDuration(NSTimeInterval(1.0), animations:{()-> Void in 
      self?.warningLabel.alpha = 1.0 
     }) 

Il blocco animazione finale mostra un errore nel modulo.

Cannot invoke 'animateWithDuration' with an argument list of type '(NSTimeInterval), animations:()-> Void)' 

se chiamo questo da qualche parte al di fuori della chiusura di completamento funziona.

risposta

39

Il problema è che la chiusura è implicitamente tornando il risultato di questa espressione:

self?.warningLabel.alpha = 1.0 

ma la chiusura in sé è dichiarato come il ritorno Void.

Aggiunta di un esplicito return dovrebbe risolvere il problema: Soluzione

UIView.animateWithDuration(NSTimeInterval(1.0), animations: {()-> Void in 
    self?.warningLabel.alpha = 1.0 
    return 
}) 
+0

grazie mille =) !! –

+5

Questo lo ha risolto per me, ma qualcuno avrebbe dovuto spiegare * perché * questo comportamento è così strano e inaspettato per molte persone? BTW, nel tuo esempio puoi sostituire '() -> Void' con' _' e aggiungere return usando '; ritorna alla stessa riga. INOLTRE, puoi scrivere ';() 'invece di un' ritorno 'a riga singola. :) – BastiBen

+0

Questa è la risposta corretta !!! –

0

di Antonio si applica anche con chiusure nidificati, come fare una richiesta AFNetworking all'interno gestore UITableViewRowAction.

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { 

    let cleanRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Do Stuff", handler: {[weak self](action: UITableViewRowAction!, indexPath: NSIndexPath!) in 

     AFHTTPSessionManager(baseURL: NSURL(string: "http://baseurl")).PUT("/api/", parameters: nil, success: { (task: NSURLSessionDataTask!, response: AnyObject!) -> Void in 

       // Handle success 

       self?.endEditing() 
       return 
      }, failure: { (task: NSURLSessionDataTask!, error: NSError!) -> Void in 

       // Handle error 

       self?.endEditing() 
       return 
     }) 
     return 

    }) 

    cleanRowAction.backgroundColor = UIColor.greenColor() 
    return [cleanRowAction] 
} 
Problemi correlati