SwiftUI won't display custom font - ios

I'm currently trying to add a custom font to my project, but I somehow won't work.
I've already added the .otf file to a font folder, checked that it targets to my project and added Fonts provided by application to Info.plist.
struct ContentView: View {
var body: some View {
Text("CLOSEST")
.foregroundColor(Color("primary"))
.font(Font.custom("HelveticaNowDisplayBold", size: 60))
}
}

If you have made sure that the Info.plist is using the correct filename:
Note if you are using Xcode 13 you may not have an Info.plist where you expect. This SO answer explains where you can find it.
That the font is available in the app's target.
You also need to make sure that you are accessing the font by the correct name.
An easy way to check the font's name is to add the following to your AppDelegate in the didFinishLaunchingWithOptions before the return true. Or if you are using the new SwiftUI lifecycle you can add it to an .onAppear.
for family in UIFont.familyNames.sorted() {
let names = UIFont.fontNames(forFamilyName: family)
print("Family: \(family) Font names: \(names)")
}
This will list all the fonts by family and name.
Just remember to remove it once you have finished using it as you don't need to unnecessarily print to the console.
When I do it for my fonts (I have added the same font as you) I find the following in the console in the list of available fonts (see the above screenshot) :
Family: Helvetica Now Display Font names: ["HelveticaNowDisplay-Bold"]
Your font may have a different name to mine, and it is important to note that the font name may not be the same as the filename. This is what trips up a lot of people, as they try using the filename when they need to use the font name.
The following test code produces:
struct ContentView: View {
var body: some View {
Text("Hello")
.foregroundColor(.blue)
.font(Font.custom("HelveticaNowDisplay-Bold", size: 60))
}
}
For more information about adding custom fonts see Apple's documentation.
Dynamic Type in SwiftUI
If you are using a custom font then you should consider setting it up so that it will scale with dynamic type.
iOS 14
iOS 14 introduces a new modifier that allows you to scale a font relative to a Dynamic Font Type.
Text("Hello")
.font(.custom("HelveticaNowDisplay-Bold", size: 60, relativeTo: .body))
iOS 13
If you are using iOS 13 that requires a bit more effort to get the same effect.
You first need to create a ViewModifier. This view modifier listens to the size category from the environment (it doesn't actually use it but having it here makes sure the view modifier is updated whenever the size category is updated).
struct ScaledFont: ViewModifier {
#Environment(\.sizeCategory) var sizeCategory
var name: String
var size: CGFloat
func body(content: Content) -> some View {
let scaledSize = UIFontMetrics.default.scaledValue(for: size)
return content.font(.custom(name, size: scaledSize))
}
}
extension View {
func scaledFont(name: String, size: CGFloat) -> some View {
return self.modifier(ScaledFont(name: name, size: size))
}
}
It is then used in the following way:
Text("Hello")
.scaledFont(name: "HelveticaNowDisplay-Bold", size: 60)
For a really good write up check out this post on Hacking With Swift.

For those people who no longer have a app/scene delegate to put this in. In your <Your_App_Name>App.swift file
init() {
for family in UIFont.familyNames.sorted() {
let names = UIFont.fontNames(forFamilyName: family)
print("Family: \(family) Font names: \(names)")
}
}
Will work

You need to include the extension of the font (for example .ttf) in the info.plist . I saw a couple of tutorials on youtube, which do not included it, but for me, it does not work without it.

I had the exact same problem. The following steps fixed it for me. I'm currently using Xcode 11.4.1
Create a storyboard, add a label and select your font in the inspector as font for the label.
Build your App in the Simulator
Check the installed fonts with:
for family in UIFont.familyNames.sorted() {
let names = UIFont.fontNames(forFamilyName: family)
print("Family: \(family) Font names: \(names)")
}
If it's appearing you can use it also programmatically
Here is also a list of Common mistakes with adding custom fonts

I had the same issue,
it worked for me when I omitted the "-Regular",
but in the info.plist I wrote it with it.

Sometimes font file name and the font actual name are different.
In my case my file name was SCRIPTIN.ttf but the actual font name was Scriptina.
I found this by running the following function in App.swift file.
init() {
for family in UIFont.familyNames.sorted() {
let names = UIFont.fontNames(forFamilyName: family)
print("Family: \(family) Font names: \(names)")
}
}
Just put this file after this function in App.swift file and run the app. You will get a list of all loaded files and their names including the newly added font.
var body: some Scene {
WindowGroup {
ContentView()
}
}
Thank you.

Xcode 13 Press on target, then info, type Fonts provided by the application and add item font name as like image

Jonas Deichelmann's answer (to list the fonts available to app) was very helpful to fine tune the Info.plist entries.
Contrary to Apple's example at https://developer.apple.com/documentation/swiftui/applying-custom-fonts-to-text that shows the Fonts provided by application entries to include a relative path to the font files including a subdirectory, I had to provide exclusively the font file name (e.g. Mulish-Regular.ttf with the file extension but without the subdirectory into which the file is stored)
Xcode 14.2

Related

Using sans-serif-condensed in compose

I'm want to use sans-serif-condensed in jetpack compose, but for the life of me, I can't find it anywhere within compose itself?
Am I just blind, or will I need to do something like import the font and set it all manually?
You can use the fontFamily attribute to specify the font family.
Text("Hello World", fontFamily = FontFamily.Serif)
Predefined Fonts
By default, Jetpack compose has only 5 Font Families,
Default, SansSerif, Serif, Monospace and Cursive.
Custom Fonts
If you need any other font family (which seems to be your case), you have to add it as mentioned here.
Steps
Download or Get the required fonts files and add them to the res/fonts directory.
Create FontFamily like this,
val firaSansFamily = FontFamily(
Font(R.font.firasans_light, FontWeight.Light),
Font(R.font.firasans_regular, FontWeight.Normal),
Font(R.font.firasans_italic, FontWeight.Normal, FontStyle.Italic),
Font(R.font.firasans_medium, FontWeight.Medium),
Font(R.font.firasans_bold, FontWeight.Bold)
)
Use like this,
Text(..., fontFamily = firaSansFamily, fontWeight = FontWeight.Light)
Text(..., fontFamily = firaSansFamily, fontWeight = FontWeight.Normal)

DevExtreme's DataGrid exportToPDF displays gibberish when used on a table with Russian values in it

When I try to export to PDF DataGrid with Russian values in it, it displays gibberish in this new PDF file even though I managed to set a proper font (PTSans) for jsPDF and when you print just random text it is working fine…
So is there a way to configure table to PDF to display proper Russian?
Actually I suddenly found a solution :D
If anyone will ever have this problem again, this is how you solve it:
const doc = new jsPDF();
const font = "../../../assets/fonts/PTSans-Regular.ttf" // path to .ttf file
doc.addFont(font, "PTSans-Regular", "normal");
exportDataGridToPdf({
jsPDFDocument: doc,
component: grid,
autoTableOptions: {
styles: {
font: 'PTSans-Regular' // this is a part I forgot about before
}
}
}).then(() => {
doc.save(filename);
})
Basically you need to set up font for your language in jsPdf as well as set up the same in styles for jsPDF-autoTable options.
Huge thanks to Alisher from DevExpress Support whose answer helped me to figure it out.

UpdateTextStyle Request Clearing Bold When Setting fontFamily

I am trying to update the font of a range of text in a Google Docs document using the API. I am trying to change just the font and not the font size or style attributes like bold or italic. So if for example I have a document with just the text below as the content:
Hello world
I want to change just the font for the word Hello but leave it the same size and still bold and italic.
I tried to accomplish this with the following code documents.batchUpdate request
{
"requests": [
{
"updateTextStyle": {
"range": {
"startIndex": 1,
"endIndex": 6
},
"textStyle": {
"weightedFontFamily": {
"fontFamily": "Times New Roman"
}
},
"fields": "weightedFontFamily"
}
}
]
}
The result is a successful response from the server but when I check the document I see it changed the font keeping the size and italic attribute, but it didn't keep the bold attribute. I have also tried this using the Google API Explorer and can reproduce the same results.
My question is how do I change the font without loosing the bold? It seems like it should be possible as it kept the italic attribute in tact. Why is bold different? Is it a bug?
My goal is to just change the font leaving the other attributes as is so I do not want to set bold or other attributes explicitly. I also don't want to have to determine the attributes before hand and reset them. That is more work and will be slower and shouldn't be necessary if italic is maintained.
I am able to do something very similar without issue in Google Sheets using a repeatCell.cell.userEnteredFormat.textFormat.fontFamily request and it maintains the bold and italic.
Thanks in advance for any insight or help.
How do I change the font without loosing the bold?
Answer
You have to first save the font weight and bold settings for the range of text you want to modify. There may be more then one font setting for the range. To get the font weight and bold settings for the range you must first check textRun.textStyle. If not defined there you must lookup the paragraphs namedStyleType and check it for the weight and bold settings. If not defined there you must check the NORMAL_TEXT namedStyleType. If not defined there you must use the Google Docs editor default value which for weight is 400 and bold is false.
Once you have the font info for the range you make make a requests for each different font. The request would be like the one in the original question but would set the weightedFontFamily.weight and the bold attributes based on the saved font info.
{
"requests": [
{
"updateTextStyle": {
"range": {
"startIndex": 1,
"endIndex": 6
},
"textStyle": {
"weightedFontFamily": {
"fontFamily": "Times New Roman"
"weight": savedWeight
},
"bold": savedBold
},
"fields": "weightedFontFamily"
}
}
]
}
Why is bold different?
Answer
The Google Docs API uses weightedFontFamily where the weight sub-attribute defaults to 400 and not the current font weight. The bold setting just increases the weight, so bold and weight are linked. There is no current way in the API to set just the font leaving weight/bold alone.
Is it a bug?
Answer
Based on a reply from #Tanaike I have reported the issue to Google via the Google Issue Tracker (https://issuetracker.google.com/165029692). They informed me it was working as intended.

Label in storyboard don't take the right localization value

I've built an application and now it's time to translate it to different languages. But some labels that I think I have localised don't get displayed in different languages with the different values.
Image one: So first, I've added the Swedish language inside
"Project -> Localizations"
Than I went inside the "LaunchScreen.storyboard" and edited the file.
This one:
Edited to this:
After that I made sure my launch screen supports the language like this:
And for the last step.. I edited the application language to Swedish like this:
But when I run it on the simulator, the text is not getting translated. It still remains the same text, and I've no idea how to solve it. Do you? Do not hesitate to help me out, I would really appreciate it!
So, I'm not sure if I've to add some code or whatever to make this work, but I followed a guide, and they don't. That's one of the reasons why I'm so confused. And thanks in advance!
BEFORE DISLIKE: At least give me a reason for it, so I can improve it in the future!
Since storyboards elements ids changes and they are not managable to be used as "keys" in your localized "key-value" pair one better solution when localizing storyboards (UI) elements could be to provide a custom User Define Attribute defined as a Locale Key to be used for that UIView.
Then you can define in your Storyboard Attribute Inspector for a specific UI View an input field that will be filled with the localized key defined in your Localizable.strings files (one for English one will be for Swedish, both should have the same keys but with different values - in the English one will have english translations in values, and in Swedish one the opposite.
1) For example since you want to localize a UI View UILabel than you can have this in a swift file Localizable.swift for example (the code makes possible:
import UIKit
// MARK: Localizable
public protocol Localizable {
var localized: String { get }
}
extension String: Localizable {
public var localized: String {
return NSLocalizedString(self, comment: "")
}
}
// MARK: XIBLocalizable
public protocol XIBLocalizable {
var localeKey: String? { get set }
}
extension UILabel: XIBLocalizable {
#IBInspectable public var localeKey: String? {
get { return nil }
set(key) {
text = key?.localized
}
}
}
2) You can uncheck your storyboard translations so you will endup having 1 storyboard without duplicating the storyboard into multiple translated version.
3) You can create now a Localizable.strings file containing your keys and translations and localize this file in order to have your translations (as you did with the storyboard, but instead of localizing the storyboard into multiple translated version, you will localize the Localizable.strings file (so you will see two files after you localize that in both languages, one will be called Localizable.strings (English) and the other Localizable.strings (Swedish).
Your Localizable.strings (English) could look like this for example:
"main_page_title_label" = "Main Page Title in English";
Your Localizable.strings (Swedish) could look like this for example:
"main_page_title_label" = "Huvudsida Titel på engelska";
4) Now go to your LaunchScreen.storyboard which you should have un-localized so you only have one version of it and not two like in your example pictures (English, Swedish). Look for the UILabel you want to localize and under the Attribute Inspector you will see a new input field called Locale Key here you can put as a value main_page_title_label. And now you have just localized a UILabel in your storyboard.
5) To test it from the simulator you have to change the language in Edit Scheme > Run > Options > Application Language and after you save it you can now run the app in the simulator and it will simulate that your simulator OS system will be set to Swedish language, so the label set with that key will show the Swedish value for that key.
Supporting more UI Views (UIButton, UITextField, UISearchBar..)
If you want to be able to localize more UI View, and not just UI View of type UILabel than you can add more support to the Localizable.swift file.
If you want to be able to localize also a UI View of type Button you can add this to Localizable.swift:
extension UIButton: XIBLocalizable {
#IBInspectable public var localeKey: String? {
get { return nil }
set(key) {
setTitle(key?.localized, for: .normal)
}
}
}
To support localization in storyboards for UITextField and UISearchBar placeholder text add this to your Localizable.swift:
// MARK: Special protocol to localizaze UI's placeholder
public protocol UIPlaceholderXIBLocalizable {
var localePlaceholderKey: String? { get set }
}
extension UITextField: UIPlaceholderXIBLocalizable {
#IBInspectable public var localePlaceholderKey: String? {
get { return nil }
set(key) {
placeholder = key?.localized
}
}
}
extension UISearchBar: UIPlaceholderXIBLocalizable {
#IBInspectable public var localePlaceholderKey: String? {
get { return nil }
set(key) {
placeholder = key?.localized
}
}
}
I like denis_lor's solution, but I thought that I first want to get working what should be working already (translation of the storyboard with a simple strings file) without having to re-implement that functionality in a similar way.
My problem was similar to what is described in the question. Translations were already working to a point, but manually added and some changed translations didn't get translated at all.
The solution I found was recreating the strings file using ibtool:
ibtool AppName/Base.lproj/Main.storyboard --generate-strings-file tmp.strings
After backing up my current (just partly working) Main.strings file (AppName/de.lproj/Main.strings) I overwrote it with the newly generated tmp.strings
mv tmp.strings AppName/de.lproj/Main.strings
And then I manually changed the values of that file to the backed up values.
Now everything gets translated correctly again. I think the problem could have had something to do with encoding problems, because that strings files are UTF16 encoded.
According to Apple docs, the LaunchScreen.storyboard is static and shouldn't have texts because these texts will not be localized.
Avoid including text on your launch screen. Because launch screens are static, any displayed text won’t be localized.
source: https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/launch-screen/

How to display labels with custom ttf?

Apparently is is possible to use Cocos2d-js 3.0 RC3 cc.LabelTTF with custom fonts, for example as answered here. However this doesn't seem to produce any results for me, neither in the local JSBinding app nor in the web browser.
Font file was included in the res object:
var res = {
lobster_ttf: "res/Lobster.ttf"
};
var g_resources = [];
for (var i in res) {
g_resources.push(res[i]);
}
Lobster.ttf does exist in the directory res.
The label is instantiated as follows:
var label = new cc.LabelTTF("labeltext", res.lobster_ttf, 48);
Doing this will not display the label in the specified font but in the default font. Specifying an installed font instead of the path to the custom ttf does however work.
Is there extra work required to be able to use TTF files?
cocos2d-js v3.0 rc3
Mine worked using the font name (font name when installing the font, not the file name font)
sample:
var label = new cc.LabelTTF("labeltext", "Lobster", 48);
Give it a try..
Tim

Resources