2014-10-22 11 views
6

Ho usato questo codiceImpossibile trovare un sovraccarico per “init” che accetta gli argomenti forniti SWIFT

self.navigationController?.navigationBar.titleTextAttributes = 
     [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 20), 
     NSForegroundColorAttributeName: UIColor.whiteColor()] 

e sto ottenendo l'errore "Impossibile trovare un sovraccarico per‘init’che accetta gli argomenti forniti "

+0

leggermente diversi, ma in sostanza lo stesso problema: http://stackoverflow.com/questions/26499815/nsfontattributedstring-worked-before-xcode-6-1/26500637#26500637 –

risposta

14

UIFont(name:size:) è ora un inizializzatore disponibile - restituirà nil se non riesce a trovare quel tipo di carattere e interrompe l'app se si scollega il valore restituito. Utilizzare questo codice per ottenere in modo sicuro il tipo di carattere e usarlo:

if let font = UIFont(name: "HelveticaNeue-Light", size: 20) { 
    self.navigationController?.navigationBar.titleTextAttributes = 
      [NSFontAttributeName: font, 
      NSForegroundColorAttributeName: UIColor.whiteColor()] 
} 
0

Utilizzare questa

self.navigationController?.navigationBar.titleTextAttributes = 
     [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 20)!, 
     NSForegroundColorAttributeName: UIColor.whiteColor()!] 

o questa

if let font = UIFont(name:"HelveticaNeue-Light", size: 20.0) { 
    self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: font] 
} 
+0

si veda risposta a cura – ZAZ

+0

Non è necessario il '!' Dopo 'UIcolor.whiteColor()' in quanto non restituisce un optional. In effetti, usarlo ti darà un errore nel compilatore. – chrysAllwood

0

Un altro approccio è quello di costruire un dizionario prima di impostare titleTextAttributes. Questo ti evita il/i altro/i, il che sarebbe più vantaggioso nei casi in cui si desidera impostare ulteriori parametri utilizzando anche inizializzatori disponibili. Ad esempio: domanda

var attributes : [NSObject : AnyObject] = [NSForegroundColorAttributeName : UIColor.whiteColor()] 

if let font = UIFont(name: "Helvetica", size: 20) { 
    attributes[NSFontAttributeName] = font 
} 

if let someData = NSData(contentsOfFile: "dataPath") { 
    attributes["imageData"] = someData 
} 

self.myObject.attributes = attributes 
Problemi correlati