custom font becomes a nil value in swift 3 - ios

I want to set attributedstring to my UILabel. So I defined the attributes in this way.
let attribute1:[String:Any]=[
NSForegroundColorAttributeName: UIColor.init(colorLiteralRed: 120.0/255, green: 173.0/255, blue: 194.0/255, alpha: 1.0),
NSFontAttributeName:UIFont.init(name: "Bariol_Bold", size: 15.0)!]
let attributedStringGreeting=NSAttributedString.init(string: welcomeMessage, attributes: attribute1)
but I am getting this error in the line:
NSFontAttributeName:UIFont.init(name: "Bariol_Bold", size: 15.0)!]
Does that mean my custom font is not taking? But when I set the font from IB it shows.
fatal error: unexpectedly found nil while unwrapping an Optional value
How can I solve this issue? Please help me.

This commonly happens if actual font name is not same as file name, so the thing is how to find font name.
Take this steps,
Add all font files in your bundle
Add listing of all font files in your info.plist under key : "Font Provided By Application"
Now run the following code,
for fontFamilyName in UIFont.familyNames{
for fontName in UIFont.fontNames(forFamilyName: fontFamilyName){
print("Family: \(fontFamilyName) Font: \(fontName)")
}
}
Now see the output in your console, all the available fonts are printed here, check the actual font name of your provided fonts. Now just use the same font name as below:
Now, use that font name for UIFont.init(name: "Actual Font name comes here", size: 15.0)!]

The problem is in the name. Every time it's not necessary that the file name and Font name is similar. To know the exact font name you can use the following function.
func printMyFonts() {
print("--------- Available Font names ----------")
for name in UIFont.familyNames {
print(name)
print(UIFont.fontNames(forFamilyName: name))
}
}
Hope this helps!

Try this
let attribute1:[String:Any] = [NSFontAttributeName: UIFont(name: "Bariol-Bold", size: 18)! ,
NSForegroundColorAttributeName : UIColor.init(colorLiteralRed: 120.0/255, green: 173.0/255, blue: 194.0/255, alpha: 1.0)]
let attributedStringGreeting=NSAttributedString.init(string: welcomeMessage, attributes: attribute1)

Related

Font in iOS11 is incorrectly displayed

I have a font called Poppins-bold (you can find it on Google Font) that in iOS 11 display incorrectly. Here you can see a screenshot with iOS 10:
And screenshot in iOS 11:
Four fonts displayed are:
Poppins Bold with a Storyboard
Helvetica Bold with a Storyboard
Poppins Regular via code
Poppins Bold via code
And my error is with Poppins Bold via code. My code is:
label1.font = UIFont(name: "Poppins-Regular", size: 30)
label2.font = UIFont(name: "Poppins", size: 30)
How is it possible?
I've printed font in the projects and this is my result:
Font Family Name = [Poppins]
Font Names = [["Poppins-Regular", "Poppins"]]
Your printout explains the problem. "Poppins" is a family name. If you have both Poppins Regular and Poppins Bold, the family name defaults to meaning the regular font. This prevents you from accessing the Poppins Bold font by its name, which (unfortunately) is "Poppins".
Instead, use the font descriptor to change Poppins Regular to Poppins Bold:
let font = UIFont(name: "Poppins-Regular", size: 30)!
let desc = font.fontDescriptor
let desc2 = desc.withSymbolicTraits(.traitBold)!
let font2 = UIFont(descriptor: desc2, size: 0)
self.lab.font = font2
I might be a bit late, but in case your question is still relevant, problem can be solved by updating font files from https://fonts.google.com/specimen/Poppins. You will also need to use "Poppins-Bold" font name instead of "Poppins".

Font is nil when setting NSFontAttributeName

I'm trying to change my font from medium to regular, but I keep getting nil when setting the font type for NSFontAttributeName. I can get the font as medium without a problem, but when I try to set it to regular programmatically, my program crashes because the font is nil.
let attrsUnselected = [NSFontAttributeName: UIFont(name: "Roboto-
Regular", size: 15)!, NSForegroundColorAttributeName : UIColor.gray]
let attrsSelected = [NSFontAttributeName: UIFont(name: "Roboto-Medium",
size: 15)!,NSForegroundColorAttributeName : UIColor.black]
Before my app crashes, I can see that the font is actually set to regular.
I don't know how many different ways I get validate that the font has been imported into the project.
Check the following:
The font is added to the target
Its listed under "Copy Bundle Resources" on your target
And does it show up in the list of available fonts when you print them?

Set NSFontAttributeName to have bold font

Im trying to apply on the following code to be bold with current custom font , how do i include it in the dictionary ?
let normalWhite = [NSFontAttributeName : UIFont(name: "somefont", size: 16.0)!,NSForegroundColorAttributeName : UIColor.whiteColor()]
I think you should include the custom bold font file in your Xcode and write its name like Helvetica-Bold

How to access the iOS system font programmatically

I am trying to change the font size of the title of a navigation bar. I know I can set its attributes using:
var attributes = [ NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont(name: "the font name", size: 18)! ]
...
self.navigationController?.navigationBar.titleTextAttributes = attributes
What I cannot seem to find is the correct 'System' font name.
I was after the default, a.k.a System, font name. I tried printing all the available fonts only to discover it does not belong to a family and does not seem to have an explicit name.
I think you need:
NSFontAttributeName : UIFont.systemFontOfSize(19.0)
Or the bold version:
NSFontAttributeName : UIFont.boldSystemFontOfSize(19.0)
See this guide for more info on user interface guidelines and fonts.
You can access the system font like this, and even set the weight of the font:
Swift 3, Swift 4
UIFont.systemFont(ofSize: 18, weight: UIFontWeightLight)
Swift 2
UIFont.systemFontOfSize(18, weight: UIFontWeightLight)
For the font weight you have the choice between those constants, there available from iOS 8.2:
UIFontWeightUltraLight,
UIFontWeightThin,
UIFontWeightLight,
UIFontWeightRegular,
UIFontWeightMedium,
UIFontWeightSemibold,
UIFontWeightBold,
UIFontWeightHeavy,
UIFontWeightBlack
SWIFT 4+:
shorter version
UIFont.systemFont(ofSize: 14.0, weight: .regular)
(In line with the answer from Philippe for the latest version)
Swift 4
UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.light)
Besides all the answers, it's a better idea to use system font with system styles instead of defining custom sizes and weights. To access them programmatically, for example for the headline, you can use this method:
let font = UIFont.preferredFont(forTextStyle: .headline)
I know it is a valid code at least for Swift 5.
self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName : UIFont.systemFontOfSize(6)]
Just use methods of UIFont (swift):
let sysFont: UIFont = UIFont.systemFontOfSize(UIFont.systemFontSize())
Hope it helps!
Try the below code:
self.navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name:"Arial", size:14.0)!, NSForegroundColorAttributeName:UIColor.blackColor()]

Swift NSAttributedString custom fonts

I've read around for different solutions but nothing seems to work. This code creates a nil exception:
[NSFontAttributeName: UIFont(name: "Raleway-SemiBold", size: 16)!]
I have the fonts installed properly and they show up correctly in the app (target is set).
I tried to add the application provided fonts in the plist but nothing happened. I can't edit the items in the array: (they are item0 : string : Raleway-SemiBold.tff).
So basically I'm stuck... Sometimes Swift and Apple environments are great for a programmer, other times (most of the time), they are sooo faulty and need so many workarounds to reach the expected results.
Many thanks in advance for any help.
You're getting an exception because UIFont(name: "Raleway-SemiBold", size: 16) returns nil and you're force-unwrapping it with !.
Instead, use conditional unwrapping:
if let font = UIFont(name: "Raleway-SemiBold", size: 16) {
let attributes = [NSFontAttributeName: font]
// do something with attributes
} else {
// The font "Raleway-SemiBold" is not found
}
You can use UIFont's familyNames() and fontNamesForFamilyName(_:) methods to get the exact string required.
Swift 4
if let font = UIFont(name: "Raleway-SemiBold", size: 16) {
let attributes = [NSAttributedStringKey.font: font]
// do something with attributes
} else {
// The font "Raleway-SemiBold" is not found
}
You Just have to write the correct string name of your font.
Don't write the name that is font file name. (like bodoni-mt-bold.ttf its the file name i have downloaded from any site).
To find out the exact font name follow the image below.
Go to your label select it and go to custom font and then see the name of your custom font in its family. if your custom font name is there then copy that name and past it as a string where u wanna use it. (Note you can't copy font name text you have to write else where then past it)
For Swift 3, here's an update that worked for me:
First you'll set up the font and then create a textAttribute with the NSFontAttributeName:
let font = UIFont(name: "Raleway-SemiBold", size: 16)
textAttribute = [NSFontAttributeName: font as Any, NSForegroundColorAttributeName: UIColor.black]
You can then apply textAttribute to your label, textfield etc.

Resources