How to Create a Bold Uifont from a Regular Uifont

How do I create a bold UIFont from a regular UIFont?

To get a bold font you need to pass a specific name of the font from a font family. You can get a font family name from a given font, then list all fonts from this family. In general, a bold font will contain "bold" in its name, but the format isn't strict and there could be variations like "Helvetica-BoldOblique", for example. You can start from this code:

- (UIFont *)boldFontFromFont:(UIFont *)font
{
NSString *familyName = [font familyName];
NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
for (NSString *fontName in fontNames)
{
if ([fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch].location != NSNotFound)
{
UIFont *boldFont = [UIFont fontWithName:fontName size:font.pointSize];
return boldFont;
}
}
return nil;
}

How do I create a bold UIFont from a regular UIFont?

To get a bold font you need to pass a specific name of the font from a font family. You can get a font family name from a given font, then list all fonts from this family. In general, a bold font will contain "bold" in its name, but the format isn't strict and there could be variations like "Helvetica-BoldOblique", for example. You can start from this code:

- (UIFont *)boldFontFromFont:(UIFont *)font
{
NSString *familyName = [font familyName];
NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
for (NSString *fontName in fontNames)
{
if ([fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch].location != NSNotFound)
{
UIFont *boldFont = [UIFont fontWithName:fontName size:font.pointSize];
return boldFont;
}
}
return nil;
}

How to create bold UIFont

If you're using the version of Helvetica that is bundled in iOS, you can simply do:

[UIFont boldSystemFontOfSize:17.0];

How can I create a UIFont with bold weight but not bold style?

If you refer to the font name itself you can create them like so by using a dash:

[UIFont fontWithName:@"Helvetica-Regular" size:12]

Making UIFont Black/Heavy and Italic

I tested like this:

let weights : [UIFont.Weight] = [
.ultraLight, .thin, .light, .regular,
.medium, .semibold, .bold, .heavy, .black
]
var top : CGFloat = 25
for weight in weights {
let desc = UIFont.systemFont(ofSize: 32).fontDescriptor.addingAttributes([
UIFontDescriptor.AttributeName.traits: [
UIFontDescriptor.TraitKey.weight:
weight.rawValue,
UIFontDescriptor.TraitKey.symbolic:
UIFontDescriptor.SymbolicTraits.traitItalic.rawValue
]
])
let lab = UILabel()
lab.font = UIFont(descriptor: desc, size: 0)
lab.text = "This is a test"
lab.sizeToFit()
lab.frame.origin = CGPoint(x: 20, y: top)
self.view.addSubview(lab)
top += lab.bounds.height + 8
}

This is what I see:

Sample Image

So it seems to me that we are getting all the different weights in an italic typestyle.



Related Topics



Leave a reply



Submit