This is strange.
This works:
titleLabel.font = UIFont(name: "OpenSans-Regular", size: 14)
This works:
attributedString.addAttribute(NSFontAttributeName, value:
UIFont(name: "OpenSans-Bold", size: 18)!,
range: ((attributedString.string as NSString).range(of: "Forgot your password? Reset it here")))
This doesn't. Gives a crash:
Unexpectedly found nil while unwrapping an Optional value
attributedString.addAttribute(NSFontAttributeName, value:
UIFont(name: "OpenSans-Regular", size: 18)!,
range: ((attributedString.string as NSString).range(of: "Email or password are incorrect."))).
First example shows that OpenSans-Regular works fine in the app. (Same font used in 3rd example).
Second example shows attributed string works fine with custom font.
Third example shows attributed string with custom font doesn't work.
I double checked, OpenSans-Regular I correctly copied in my project :
Project directory :
Copy bundle resources :
Info.plist :
You simply did not correctly add the font with name "OpenSans-Regular"
,
First line, line:
titleLabel.font = UIFont(name: "OpenSans-Regular", size: 14)
works, because titleLabel.font
is optional, thus it has no problem with UIFont(name: "OpenSans-Regular", size: 14)
being evaluated to nil. So it does not prove that "OpenSans-Regular"
was added correctly.
However, in the third example:
attributedString.addAttribute(NSFontAttributeName, value:
UIFont(name: "OpenSans-Regular", size: 18)!,
range: ((attributedString.string as NSString).range(of: "Email or password are incorrect.")))
here you are force unwrapping it (notice !
at the end of UIFont(name: "OpenSans-Regular", size: 18)!
), thus it crashes - this on the other hand proves you did not add it correctly.
EDIT
Make sure you add "OpenSans-Regular"
correctly to the project. I recommend going over the list at this blog entry, especially check point number 5 there (names).
EDIT 2
As @rmaddy pointed out, "OpenSans-Regular"
is "OpenSans"
- see this question. Therefore rather use:
titleLabel.font = UIFont(name: "OpenSans", size: 14)
And:
attributedString.addAttribute(NSFontAttributeName, value:
UIFont(name: "OpenSans", size: 18)!,
range: ((attributedString.string as NSString).range(of: "Email or password are incorrect.")))