Could not find overload for "init" that accepts provided SWIFT arguments

I used this code

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

and I get the error "Could not find overload for" init ", which takes the provided arguments

+6
source share
3 answers

UIFont(name:size:) now a fault tolerant initializer - it will return nil if it cannot find this font and break your application if you expand the return value. Use this code to safely get the font and use it:

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

Use this

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

or this

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

Another approach is to create a dictionary before setting titleTextAttributes . It just avoids you otherwise, which would be more useful in cases where you would like to set additional parameters, also using fault-tolerant initializers. For instance:

 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 
0
source

Source: https://habr.com/ru/post/977088/


All Articles