NSFontAttributedString worked before Xcode 6.1

let timeFont = [NSFontAttributeName:UIFont(name: "Voyage", size: 20.0)] var attrString3 = NSAttributedString("(Time)", attributes : timeFont); // <--- compiler error "Extra argument in call" 

This code worked in xcode 6.0, but now that I upgraded to xcode 6.1, it no longer works, and I cannot figure out what I need to get it back. It says there is an additional argument, but this is not true. I believe that it has something to do with new failed initializers, but everything I tried does not work.

+2
source share
2 answers

Xcode 6.1 ships with Swift 1.1, which supports constructors that may fail. UIFont initialization may fail and return nil . Also use string: when creating NSAttributedString :

 if let font = UIFont(name: "Voyage", size: 20.0) { let timeFont = [NSFontAttributeName:font] var attrString3 = NSAttributedString(string: "(Time)", attributes : timeFont) } 
+5
source

There are two reasons why your code is not compiled:

  • The initializer for the NSAttributedString that you want to use requires explicitly marking the string parameter
  • The UIFont initializer that you use now returns an optional (i.e., UIFont? ) That needs to be deployed before passing it to the attribute dictionary.

Try this instead:

 let font = UIFont(name: "Voyage", size: 20.0) ?? UIFont.systemFontOfSize(20.0) let attrs = [NSFontAttributeName : font] var attrString3 = NSAttributedString(string: "(Time)", attributes: attrs) 

Pay attention to the use of the new coalescence operator ?? . This deploys the optional Voyage font, but reverts to the system font if Voyage is unavailable (which seems to be the case on the playground). This way you get your attribute string regardless of whether your preferred font is loaded.

+6
source

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


All Articles