WatchKit WKInterfaceLabel can't change font - ios

I'm trying to change label font. But every font I set in the Attributes Inspector different from the system font - don't change anything - neither simulator or storyboard. I even tried to set the font programatically with Attributed string - the same System font appears. Thanks for your help.

You cannot use the included iOS fonts in WatchKit at this time. The only one available is System (San Francisco). Source: Apple Developer Forums
You can however use a custom font by adding the font file to the project:
Drag the font files into the project navigator
Include the custom font file in both your WatchKit app and WatchKit
extension bundle.
Add the Fonts provided by application (UIAppFonts) key to both your WatchKit app and your WatchKit Extension Info.plist files
Add this code to awakeWithContext to make sure you know the correct font name to call later in your code:
print("Custom font names:")
print(UIFont.fontNames(forFamilyName: "Exo"))
print(UIFont.fontNames(forFamilyName: "Tabardo"))
Run the app and take note of the font names printed to the debug console. Once you know the correct name, you can add this code somewhere in your WatchKit Extension:
var fontSize = CGFloat(32)
var text = "so cool"
var cstmFont = UIFont(name: "Tabardo", size: fontSize)!
var attrStr = NSAttributedString(string: text, attributes:
[NSFontAttributeName: cstmFont])
firstLabel.setAttributedText(attrStr)
fontSize = CGFloat(36)
text = "right on!"
cstmFont = UIFont(name: "Exo-Regular", size: fontSize)!
attrStr = NSAttributedString(string: text, attributes:
[NSFontAttributeName: cstmFont])
secondLabel.setAttributedText(attrStr)
Enjoy the custom fonts on the watch!
Keep in mind that glances and notifications cannot use custom fonts. If you want to use one there, you'll have to use a rendered image. However because glances and notifications should load quickly you'd want to have that image ready to go when it gets called.

Related

Custom font in Xcode does not work

Added custom font as tutorial suggest here.
font is in “Build Phases” -> “Bundle Resources”
font names is in your plist
But still neither from Stroyboard nor from code I can set font of an UILabel. What am I missing?
Please read carefully this article.
Step 5: Find the name of the font
This is a common pitfall for many people trying to include custom
fonts into their iOS app. This was something that eluded me before as
well and it’s the fact that when you specify which font you want to
use, you’re not specifying the file name but rather, the font name.
The tricky part is that the font name may not be what you expect. It
could be very different than any of the visible font names that you
can see.
So in order to easily find the name of the font that you want to use,
you can output something to the console window and see for yourself.
You can print names for all fonts available for developer with this code:
for family in UIFont.familyNames {
print("\(family)")
for names in UIFont.fontNames(forFamilyName: family){
print("== \(names)")
}
}
It will produce output like this:
Find yours and use it with:
label.font = UIFont(name: "SFProText-Heavy", size: 14.0)
To add custom font to interface builder open Font Book from Spotlight Search and drag and drop your font there

Custom Fonts Bug

TL;DR: Custom fonts couldn't be used programmatically before using them in a Storyboard/xib.
Note: I've checked out this, tried the answers and they didn't work. I've also made sure that they're in target membership.
I've noticed a strange bug while changing segment control title a custom font:
segmentedControl.titleTextAttributes = NSDictionary(objects: [UIFont.init(name: "Comfortaa-Regular",
size: UIFont.systemFontSize)!,
UIColor.white],
forKeys: [NSAttributedStringKey.font as NSCopying,
NSAttributedStringKey.foregroundColor as NSCopying]) as? [AnyHashable : Any]
It couldn't find the font, so unwrapping has failed. But the font could be seen in the Storyboard.
It's properly added to the project, here's the CopyBundle and InfoList:
So here's the catch; if I use it in the Storyboard, it is shown in the font families:
But if not, it's not shown -here I've changed to light and bold has disappeared-, and cannot be used programmatically.
I'm using Xcode Version 9.0 (9A235), and Swift 4. I've also checked OpenRadar and couldn't find a submission regarding this.
The mentioned font: Comfortaa
#EDUsta, I just tried with given font and its work ok, no issue in it, giving the step which i followed:
Add the Comfortaa-Bold.ttf, Comfortaa-Light.ttf, Comfortaa-Regular.ttf Font files to project.
2.Add the entries of Fonts in info.plist file
Make sure the font added in project target.
After it, apply the fonts on UILabel and UISegmentedControl using Swift code given below:
let fontFirst = UIFont(name: "Comfortaa-Bold", size: 16.0)!
segmentFont.setTitleTextAttributes([NSAttributedStringKey.font : fontFirst, NSAttributedStringKey.foregroundColor : UIColor.red],
for: .normal)
labelBold.font = UIFont(name: "Comfortaa-Bold", size: 16.0)
labelLight.font = UIFont(name: "Comfortaa-Light", size: 16.0)
labelRegular.font = UIFont(name: "Comfortaa-Regular", size: 16.0)
its work perfectly, you can check in below screenshot image:
For your reference i am adding the complete project here:
I have the same problem. I can't add exactly the same font family (Comfortaa) programatically - everytime it crashes, but once I add label in launchscreen and set font to Comfotaa-Bold, font loaded from code works fine and doesn't crash. So my solution is to add 3 labels with fonts such as - Comfortaa Bold, Comfortaa Regular, Comfortaa Light in launchscreen and set "hidden" flag on true. This way I'm able to use all of them programatically.

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.

Setting other font than system in WatchKit (Apple Watch)

I have one Apple Watch app that is using Menlo Bold font for label.
In first version of Xcode that supported watchkit I was able to change font of label in storyboard to Menlo Bold 36 and everything was working fine.
In curent version (Xcode 6.2) that is not possible any more, so I found this tutorial on how to set custom font in Apple Watch, http://www.tech-recipes.com/rx/53710/how-do-i-use-custom-fonts-in-my-apple-watch-app/
I this tutorial I found this code:
func printFonts() {
let fontFamilyNames = UIFont.familyNames()
for familyName in fontFamilyNames {
println("------------------------------")
println("Font Family Name = [\(familyName)]")
let names = UIFont.fontNamesForFamilyName(familyName as String)
println("Font Names = [\(names)]")
}
}
This code print available fonts.
It is used to see why is the name of the font that you have added.
At this stage I have not added any custom font, but I run this function just to see what font are available on Apple Watch by default.
After running this I found:
/* lot of fonts before */
------------------------------
Font Family Name = [Menlo]
Font Names = [[Menlo-BoldItalic, Menlo-Regular, Menlo-Bold, Menlo-Italic]]
------------------------------
/* lot of fonts after */
It look like that my Menlo-Bold is available on Apple Watch, but I just can not select it in StoryBoard.
So , I was think this is very good, I do not need to add font I will just use it.
This is my code:
// must maee attributed text
let attributedTextForHour = NSAttributedString(
string: "IS IT WORKING",
attributes: NSDictionary(object: UIFont(name: "Menlo-Bold", size: 36)!, forKey:NSFontAttributeName))
// with atributex text
mylabel.setAttributedText(attributedTextForHour)
When I run this code in simulator, font of the label is not changed.
And here are some other strange things:
in debugger, when I set break point on mylabel.setAttributedText(attributedTextForHour) and do quick look on attributedTextForHour it is showed in correct font.
So in debugger it is fine, but on simulator it is not.
So how to fix this ?
I do not have Apple Watch, so I can see what is happening on real device.
So, I do no know is there some problem in my code or this is bug form Apple.
If somebody can test this on the is computer and report results, that will be useful also.
Maybe whole problem is because I have not added Menlo Bold font from outside and I am using what printFont() function has shown.
So if anybody know where I can download Menlo Bold font, please provide link, so that I can test that also.
I manage to solve this problem, so I am posting for future generations.
There are few things that I have learned from this (after 3h of work)
Font that are by default printed by printFonts() they look-like that are available but they are not.
you can add your *.otf font by following http://www.tech-recipes.com/rx/53710/how-do-i-use-custom-fonts-in-my-apple-watch-app/ and then you can just select it in Storybord by custom font, so you do not need to make NSAttributedString
If you want to add font that is already printed in printFonts() that things become complicated.
You can not add it by same name, so you must add it with different name, I called it Menlo-Bold-My.otf, and you must change some ID of font.
So Menlo-Bold-My.otf is same as Menlo-Bold.otf from Apple.
For converting, manipulating fonts I used program http://fontforge.github.io/en-US/

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