changing custom font for UILabel using custom fonts (programatically) in swift - ios

First off, I do realize this has been asked multiple times. Unfortunately the most common answer, isn't working in my case, so please read the full question :)
Here's what I did when I added my custom fonts to the project:
made a folder/group in my project called "Fonts"
added my fonts to that group. (I made sure both the project and "Projetname Tests" was checked as targets)
I checked my project file, -> Build phases -> Copy Bundle resources that the fonts were in there, which they are.
I went to my Plist. and added the group called "Fonts provided by Application", in there I added an item for all my fonts, and changed the strings to the font names
and lastly here's the code that I tried changing the font of a simple label with:
var label = UILabel(frame: CGRectMake(100, 70, 200, 200))
label.text = "BE ON THE"
label.font = UIFont(name: "BabasNeue", size: 106)
self.view.addSubview(label)
The label shows up when I run the app, but neither the size or the font changes.
if anyone wants to check the fontnames are correct, here's the font I'm trying to use: http://www.fontsquirrel.com/fonts/bebas-NEUE
Lastly, I just want to quickly mention that I am fully able to change the font of any labels to my custom fonts using storyboard. But I cannot get it working through code. :/

I think you've got a typo. It has to be called BebasNeue but you named it BabasNeue, with an a instead of an e. It needs to be the exact same name as set in the font-file.

Related

Xcode 8 custom font doesn't show up in interface builder

I am trying to use custom font (Bebas Neue) in my iOS application. The steps I took are:
Copy the .otf files to the project.
Confirm the .otf files have set the project as target.
Added the .otf files in 'Fonts provided by application' in plist.
In Build Phases, the .otf files are in 'Copy Bundle Resources'.
Install the font on my Mac.
Try to print out all fonts available but I can't see my custom font.
The code I used:
for name in UIFont.familyNames() {
println(name)
if let nameString = name as? String
{
println(UIFont.fontNamesForFamilyName(nameString))
}
}
Trying to set the font in code and it worked.
The code I used:
textLabel?.font = UIFont(name: "BebasNeueRegular", size: 14)
But I can't set it in interface builder. Any idea?
Screenshots:
Try Below Steps: Code tested in Swift 3.
Step 1: Add Your custom font into your project( Make sure Add to Target
ticked).I am using "PermanentMarker.ttf","Pecita.otf" and "AROLY.ttf" font as a test font.
Note: Supporting font Type ttf and otf (Both font types should work)
Step 2: Modify the application-info.plist file.
Add the key "Fonts provided by application" in a new row and add "PermanentMarker.ttf" as new item in the Array "Fonts provided by application".
Your plist should looks like this
Now the font will be available in Interface Builder. To use the custom font in code we need to refer to it by name, but the name often isn’t the same as the font’s filename
Now, You can access the Custom Font from your viewController. I am testing the font by placing a UIlabel to the Storyboard like below.
Update 2: Working Solution
After, imported your custom font and updated your plist.selectlabel from your storyBoard,goto Attributes Inspectorunder Label>Text type> select to Attributed and choose your custom font from the list.
Output:
Update 1
If your custom font still not listed in Xcode font list.check the related link to your issue
http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/
custom font not displaying on some simulator
Note: Still,You can assign BebasNeue or custom font programatically to your label or button etc. even its not showing in your interface Builder.If you having trouble setting font to your object programatically.try below method.
Assign font to UILabel:
label?.font = UIFont(name: "BebasNeue", size: 35) // Set to any size
Assign font to UIButton:
button.titleLabel?.font = UIFont(name: "BebasNeue", size: 35)
Assign font to UITextField:
textField.font = UIFont(name: "BebasNeue", size: 25)
Assign font to UINavigationBar:
navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "BebasNeue", size: 25)!, NSForegroundColorAttributeName: UIColor.red]
Assign font to UIToolBar:
UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "BebasNeue", size: 25.0)!], for: UIControlState.normal)
Output:
Its Easy and simple now- Tested in Xcode 10 and swift 5
Steps to add font to your Xcode
Select your UILabel, UITextField or whatever then under fonts section and follow
Step 1
Select settings menu from left corner of font selection screen. And choose font manager option.
Step 2
Click on the add button as marked below.
Step 3
Select the folder that contains your font. It will be loaded into XCode fonts list.
Steps to add fonts to your project
Don't forget to add description to your plist with the key Fonts provided by application and put font files inside copy bundle resources under project target settings.
Yes! thats it.. njoy..
When using the same font (Bebas Neue), I experience the exact same problem: the font does not show up in the font list for Plain controls.
It does for Attributed controls, as described in Update 2 in Joes post, but then you're actually changing the attributedText instead of the regular text, which may lead to unwanted behavior. For example, you'll have to fiddle with NSMutableAttributedString to change the text or text color at runtime.
I did some investigation on this issue. I used FontLab Studio to modify the font and do some tests. I used Bebas Neue version 1.400 (dated September 15, 2014) from dafont.com.
Maybe the font file was somehow corrupted. Re-saved as .otf and .ttf: Didn't work.
Maybe the meta data of the font were corrupted. Copied all the glyphs to a new font and named that Bebas Neue: Didn't work.
I renamed the font from Bebas Neue to BN: It works! But why?
Maybe you can't use "Neue" in a font name (since Helvetica Neue was the iOS system font up to iOS 8). Renamed the font to Test Neue: Still works.
Maybe you can't use "Bebas" in a font name then? Renamed the font to Bebas: Still works.
What... Just to be sure, I changed the font name back to Bebas Neue: Doesn't work again.
I also tried BebasNeue: Also didn't work.
Then I changed the name to Bebas Neue Whatever: It works.
I really do not understand why this is happening.
Doesn't Apple or Xcode want you to use "Bebas Neue" or "BebasNeue" in the Interface Builder?
I had the normal Bebas Neue installed. Maybe the reference got corrupted?
I really can't tell. Maybe someone on a clean system can try if Bebas Neue works in their Xcode.
Anyway, I achieved my goal: being able to use Bebas Neue (I named the final version "Bebas Neue MyAppName") for Plain styled labels and buttons, so I can design my app as-is and don't have to fiddle around with attributed strings.
Finally, I found the root cause of issues with Bebas Neue fonts.
I don't remember where I have downloaded the fonts, but Bebas Neue fonts are inconsistent.
Download i.e. app called Typelight
Open not Regular, but i.e. Bold font with Typelight.
You need correct most of the Bebas Neue fonts.
maybe there is a difference between folder name and font name the solution would be:
Print all default fonts names.(without custom fonts)
Add custom fonts to project.
Print all fonts names.
and after that compare fonts names.
func printFontsNames() {
let fontFamilyNames = UIFont.familyNames
for familyName in fontFamilyNames {
print("------------------------------")
print("Font Family Name = [\(familyName)]")
let names = UIFont.fontNames(forFamilyName: familyName )
print("Font Names = [\(names)]")
}
}
You can actually just go into attributed fonts, click the custom font window. There click the gear in the upper left and click on the option manage fonts. A window should pop up and on the top and there should be a plus sign to allow you to add fonts. Just choose the custom font you downloaded like xyz.tff and then it should be added.
Important to note is that ttf file should be referenced in the p-list as well as in your project directory!
TLDR
Create a new user account in Mac OS and see if you are able to have success in the new account BEFORE going through all the steps that I went through below. In hindsight, I probably could have just performed steps 7 and 11 and saved hours of hassle.
Problem
After begrudgingly upgrading to Catalina from Mojave so that I could run the latest and not greatest version of Xcode (11.5), I was no longer able to select a custom font from the font picker for PLAIN text controls within interface builder.
As others have mentioned, attributed text works fine, because it uses the systems font picker instead of the "black box / where did these fonts come from???" picker that comes up when using plain text.
Failed Steps
I tried the following steps with no success:
Re-add the font files to the project in hopes that Xcode would fix
the link to the font table that the picker is loading from (still
have no idea why there are certain fonts in the picker and where it
is getting them from).
Reset the Mac OS font caches using several terminal commands in hopes that the picker is loading the list from a corrupt font cache in the OS
Reset the system fonts by choosing File > Restore Standard Fonts in the Font Book app
Screamed at the computer and cursed Apple for what they have become
Tried installing the fonts in the OS to see if that resolved anything, because I remembered it worked a couple years ago when I ran into something similar.
Searched the internet for any clues and tried virtually everything that seemed reasonable.
Created a brand new simple project ... still could not select a custom font ... ruh oh
Bring in the Big Guns
Cursed myself for not performing a CLEAN install of Catalina and decided to reinstall Catalina from scratch.
Realized that I made a mistake using Time Machine to backup my data before re-installing, because it would not let me bring in just my data files. The Migration Assistant requires the Library data to be imported (option was grayed out when restoring), which I did not want to do ... cursed Apple and myself again because I knew this was gonna bite me in the ... as I suspected there was garbage in the profile that was causing this (I was right ... see below)
Tried to select the font in Xcode while running under the IMPORTED account from Migration Assistant ... SAME PROBLEM ... could not select a custom font
SUCCESS!!!
Created a new user and created a new simple project under that account. BINGO!!! I could select a font now!!! Somehow my user account was corrupted during the upgrade to Catalina
It was an old bug since Xcode 3.x:
there is a bug/known issue with IB on XCode 3.x with non-standard fonts and Interface Builder. Custom fonts generally need to be set programatically (via [UIFont fontWithName:])
There are some work around like this with User Defined Runtime Attribute and categories .
I had similar problem
added custom font and also assign it to UILabel all working fine but after a few times later it's wont work as expected.
Trying all solution but nothing work for me. So here is my solution, again going to previous UILabel (already have newly added custom font) select->label->select newly added font. Check other UI controls Font.
now it's working fine.
Hope this help newDevs...
This is still a recurring issue for me with Swift 4.2, even without making any changes that would cause it.
Removing the font files from the Xcode project and adding them again fixes the problem (until next time).
In my case, a font family was missing in Interface builder, because one of the fonts from that family was not added to the project, but was indicated in the info.plist file.
Generally removing all my custom fonts from the project and adding them again - fixed the issue.

TextView's font i not changing in storyboard

as you can see in the above i'm trying to change my textView's font , but it didn't changing i searched some related terms on changing for like this one
and this , but nothing worked for me
i'm also not sure if this is the correct name of my desired font or not
titleTextView.font = UIFont(name: "Myriad-Condensed", size: 25)
even in this site they dont have anything related to my desired font which is Myriad pro Condensed according to storyboard's attribute inspector
anyone faced anything similar to this before ?? or any clue what i should do ? then please let me know
First you need a font to use. Download any of them in you cass its right here : http://ufonts.com/fonts/myriadpro-cond.html
After downloading drag & drop the font file (otf or ttf) into your project
Make sure you check the box next to your target or the font won’t actually get included in your app (even though it’ll probably show in Interface Builder).
Open up the Info.plist . Add a new array of strings to it: “Fonts provided by application”. Add the filenames for each font you want to use as String entries in the array. (That one ttf file you just added to your project )
Now you're good to go , select that font once again like you did in the attached image.
For more detail see this article https://grokswift.com/custom-fonts/

IOS 8, custom font issue

I added a custom Chinese font to my project, (followed the instruction here). I only want to set the font for a few buttons, but when i do this in code or in storyboard, all the other labels, buttons, textFields.. are all set to this font too. And this only happens to ios8, and it works fine on ios9. Why did this happen, can anyone help?
this is my code to set the font:
UIFont *hannotate = [UIFont fontWithName:#"Hannotate SC" size:18];
self.button1.titleLabel.font = hannotate;
self.button2.titleLabel.font = hannotate;
this is what i set in storyboard:
Updation1:
this is screenshot of my Info.plist, I have change the font name everywhere to "FHTHannotateSC".
Updation2
I printed all the fonts in ios 8 system, and found i was using the font family name(Hannotate SC) as the font name, the real font name is "HannotateSC-W5", so i corrected the font name, and run the APP again, but unluckily, the font is still global set.
I solved this problem by doing following steps:
1. Go to project target
2. Choose Build Phase option
3. Add the font files in Copy Bundle resources.
May this help you!

How to display icon using font ? ios

I got a file(please find attached file) which contain font, this font supposed to display icons according to code number.
but i didn't succeed to display any icon with this font. here is my code:
iconTest = UILabel();
iconTest.frame = CGRectMake(0, 0, 100, 100);
onTest.center = self.view.center;
iconTest.font = UIFont(name: "icomoon", size:16.0);
iconTest.text = "e906";
what's the correct way to display icons using font !
download font svg file
You have to set text property like:
iconTest.text = "\u{e906}";
Do not forget to register your custom font in your app.
Follow these steps:
Install fonts by double clicking on them.
Drag and drop fonts in Xcode and make sure they are added to target. (check copy items if needed)
In info.plist, set key Fonts provided by application and add font name for item(under key)
Set font type custom in storyboard for your controls or programatically assign font to UILabel
Code:
//In swift 3
let font = UIFont(name: "iconmoon", size: 15)
btnSignout.setTitle("\u{e913}", for: UIControlState.normal) // set font icon on UIButton
btnSignout.titleLabel!.font = font
// In objectiveC
_lbl.text = [NSString stringWithUTF8String:"\ue92e"]; // set font icon on UILabel
_lbl.font = [UIFont fontWithName:#"iconmoon" size:16];
Note: \u prefix is mandatory, Example for unicode e626, the label text should be \ue626 or \u{e626}
I use icon font in some of my projects. I have create a project to use icon font easily. The README of this project is written in Chinese. But the demo project will show everything clearly. https://github.com/JohnWong/IconFont
Icon font is always used in UILabel by setting text. But I think creating a UIImage from font is more flexible. This is why I create this project.
Method of register font by setting project is in answer provided by martin. Here is a way to register font by code: https://github.com/JohnWong/IconFont/blob/master/IconFont/TBCityIconFont.m#L16
Icomoon.swift: Use your Icomoon fonts with Swift - auto-generates type safe enums for each icon.
Despite it's not IcoMoon, this library is worth noting:
https://github.com/0x73/SDevIconFonts
It integrates FontAwesome, Ionicons, Octicons and Iconic as Icon Fonts.
Assign them with code as easy as:
label.font = UIFont.iconFontOfSize(.FontAwesome, fontSize: 50.0)
label.text = String.fontAwesomeIconWithName(.Twitter)
As noted before, you have to register the font files in your app's Info.plist.
Anyway, regarding IcoMoon: I would use the above library as a starting point. Should be fairly easy (*) to add IcoMoon in a fork (or better as a pull request).
(*) technically spoken, adding a list of convenience shortcuts like .Twitter is quite an expensive task when I have a look at https://github.com/0x73/SDevIconFonts/blob/master/SDevIconFonts/Classes/FontAwesome.swift.

custom font not working programmatically in swift

I've followed the step to to add custom fonts in xcode at swift day-by-day and
custom fonts but I'm not able to set that font in app label programmatically.
var labeladd = UILabel(frame: CGRectMake(40, 50, 70, 22))
// label.center = CGPointMake(160, 284)
/// labeladd.font=UIFont.boldSystemFontOfSize(15)
labeladd.font = UIFont(name:"Source Sans Pro",size:15)
labeladd.textColor=UIColor.blackColor()
labeladd.textAlignment = NSTextAlignment.Center
labeladd.text = "this is custom fonts"
myview.addSubview(labeladd)
Let's say you want to add this font: SourceSansPro-Regular.otf
Four steps:
Add the font file SourceSansPro-Regular.otf to your project, make sure you select your target in the "Add to targets".
Go to the target's Build Phases and make sure it is under Copy Bundle Resources. If not, add it.
2. Go to the target's Info. Add a new entry Font provided by application then add a new item with this value SourceSansPro-Regular.otf.
From your finder, double click on the file SourceSansPro-Regular.otf, it might ask you to install the font to your Font Book.
Open the OS X Font Book application, navigate to your font then press Command+i. Note the PostScript name and use that name in your Swift code. In this case, it's SourceSansPro-Regular.
So in your code:
labeladd.font = UIFont(name:"SourceSansPro-Regular", size:15)
I've found (XCode 12) that unless your font happens to be already used in your Main.storyboard, that even if you have done all the correct steps of registering the font file in your app, copied to your bundle resources, used the PostScript name, yadda, yadda, that it still didnt show up and trying to use it in UIFont(name: size:) would still return nil. :-(
I worked around this current bug (?) by manually registering all my custom fonts at startup in AppDelegate application(_ application: didFinishLaunchingWithOptions:)
let fonts = Bundle.main.urls(forResourcesWithExtension: "ttf", subdirectory: nil)
fonts?.forEach({ url in
CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)
})
(adapted from Xcode: Using custom fonts inside Dynamic framework)
Sometimes the name of the font is not the name of your file. I was trying to use the NexaBook.otf font with the name "NexaBook" and at the end the problem was that the right name of the font is "Nexa-Book".
To check you are using the right name write this code in the viewDidLoad and check the name of the font:
for family: String in UIFont.familyNames
{
print(family)
for names: String in UIFont.fontNames(forFamilyName: family)
{
print("== \(names)")
}
}
In my case I got:
...
Nexa
== Nexa-Book
Avenir Next
== AvenirNext-Medium
== AvenirNext-DemiBoldItalic
== AvenirNext-DemiBold
...
I get this idea from Common Mistakes With Adding Custom Fonts to Your iOS App where you can find a great description of the problems working with custom fonts.
(1)First select the "Font" folder then make sure it's selected.
If you are getting the font in storyboard but not in font family and are not able to set it progammatically, then the reason is that the Xcode might not have compiled the font. To solve it:
Set the required font(say: Roboto Bold) as the font of any UI element on storyboard E.g UILabel.
Run the project
Now check the font family names. The required font(say: Roboto Bold) name would have appeared in it.
Now you can set the required font(say: Roboto Bold) progammatically :)
I was struggling with the issue quite a long time. It turned out that I forgot to add a .ttf / .otf extension to the font name in Info.plist.
Follow Apple Guide to:
Adding a Custom Font to Your App
Beyond this, I've found that if your font is not already present in a Storyboard item, UIFont.familyNames.sorted() won't list it.
The workaround is to make a storyboard, you can leave unused, and add there a UILabel for each custom font you want to be available programmatically, and then set your font as custom font from properties panel.
This is not clean solution, but I didn't find any other solution.
Best regards.
/GM
If you are adding a custom font within a framework, you need to manually load the font in app delegate before using it.
Xcode: Using custom fonts inside Dynamic framework

Resources