If I have a UIFont
object, is it possible to convert it to bold? I don't know the font name, I just have a UIFont object. What I want is a function like
UIFont *boldFontFromFont(UIFont *input)
{
return [input derivedFontWithFontWeight:UIFontWeightBold];
}
How can I change the code so that it works. (The code above does not work, I just made it up to illustrate the point.)
Thanks in advance.
iOS 7 introduces a new UIFontDescriptor class, which makes it a lot easier:
UIFont *font = [UIFont fontWithName:@"Helvetica Neue" size:12];
NSLog(@"plain font: %@", font.fontName); // “HelveticaNeue”
UIFont *boldFont = [UIFont fontWithDescriptor:[[font fontDescriptor] fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold] size:font.pointSize];
NSLog(@"bold version: %@", boldFont.fontName); // “HelveticaNeue-Bold”
UIFont *italicFont = [UIFont fontWithDescriptor:[[font fontDescriptor] fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitItalic] size:font.pointSize];
NSLog(@"italic version: %@", italicFont.fontName); // “HelveticaNeue-Italic”
UIFont *boldItalicFont = [UIFont fontWithDescriptor:[[font fontDescriptor] fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic] size:font.pointSize];
NSLog(@"bold & italic version: %@", boldItalicFont.fontName); // “HelveticaNeue-BoldItalic”
For people who got here looking for a Cocoa (macOS) equivalent, UIFontDescriptor
comes from NSFontDescriptor
, available since 10.3.
And if you are looking for the swift implementation:
let normalFont = UIFont(name: "FONT_NAME", size: CGFloat(20))!
let boldFont = UIFont(descriptor: normalFont.fontDescriptor.withSymbolicTraits(.traitBold)!, size: normalFont.pointSize)
Hope this helps! Cheers!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With