How to get the font-size or a bold-version of UIFont instance How to get the font-size or a bold-version of UIFont instance ios ios

How to get the font-size or a bold-version of UIFont instance


This is an old answer and it's no longer the best solution, please see the accepted answer instead.

-(UIFont *)boldFont{//First get the name of the font (unnecessary, but used for clarity)NSString *fontName = self.fontName;//Some fonts having -Regular on their names. so we have to remove that before append -Bold / -BoldMTfontName = [[fontName componentsSeparatedByString:@"-"] firstObject];//Then append "-Bold" to it.NSString *boldFontName = [fontName stringByAppendingString:@"-Bold"];//Then see if it returns a valid fontUIFont *boldFont = [UIFont fontWithName:boldFontName size:self.pointSize];//If it's valid, return itif(boldFont) return boldFont;//Seems like in some cases, you have to append "-BoldMT"boldFontName = [fontName stringByAppendingString:@"-BoldMT"];boldFont = [UIFont fontWithName:boldFontName size:self.pointSize];//Here you can check if it was successful, if it wasn't, then you can throw an exception or something.return boldFont;}


To access the font size from your UIFont instance use

 @property(nonatomic, readonly) CGFloat pointSize

There are more property to tell the font size (for cap, small etc...)

capHeight,xHeight,pointSize 

Use below to access the bold font

UIFont* myboldFont = [UIFont boldSystemFontOfSize:11];


UIFontDescriptor is pretty powerful class and can be used to get bold version of the font you want. It should be totally safe and future proof as it only requires usage of public API and doesn't depend on any string modifications.

Here is the code in Swift 3:

extension UIFont {    func bold() -> UIFont? {         let fontDescriptorSymbolicTraits: UIFontDescriptorSymbolicTraits = [fontDescriptor.symbolicTraits, .traitBold]         let bondFontDescriptor = fontDescriptor.withSymbolicTraits(fontDescriptorSymbolicTraits)         return bondFontDescriptor.flatMap { UIFont(descriptor: $0, size: pointSize) }    }}

Here is the code in objective-c:

@implementation UIFont (RABoldFont)- (UIFont *)ra_boldFont{    UIFontDescriptor *fontDescriptor = [self fontDescriptor];    UIFontDescriptorSymbolicTraits traits = fontDescriptor.symbolicTraits;    traits = traits | UIFontDescriptorTraitBold;    UIFontDescriptor *boldFontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:traits];    return [UIFont fontWithDescriptor:boldFontDescriptor size:self.pointSize];}@end