Kim Riegel Kim Riegel - 1 year ago 96
iOS Question

How to set font on Title of Button Objective-C

I am trying to set the font of a title on a button. I read from Apples Documentation on Fonts in Objective C and tried to implement but its not changing the font . I also tried this post... setting UIButton font. I got my font from google fonts..."Nunito-Black.tff"

Here is my code below,

- (void)addHeaderButton {

_headerButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.headerButton.frame = self.bounds;
self.headerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[self.headerButton setTitleColor:[UIColor colorWithRed:(0.0/255.0) green:(51.0/255.0) blue:(102.0/255.0) alpha:(1.0)] forState:UIControlStateNormal];
self.headerButton.titleLabel.font = [UIFont fontWithName:@"Nunito-Black" size:25];
//[self.headerButton setFont:[UIFont systemFontOfSize:25]];
[self.headerButton addTarget:self action:@selector(headerButtonAction:) forControlEvents:UIControlEventTouchUpInside];

[self.contentView addSubview:self.headerButton];
}

Answer Source

Here is the steps for adding custom fonts into your app.

Step : 1

Add your custom fonts to your app bundle and your Info.plist with UIAppFonts (Fonts provided by application) key. It's look like below image

enter image description here

Step : 2

Get the custom added font name using below snippet

[Objective-C]

for (NSString *familyName in [UIFont familyNames]){
        NSLog(@"Family name: %@", familyName);
        for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
            NSLog(@"--Font name: %@", fontName);
        }
    }

[Swift - 3]

for family in UIFont.familyNames {
            print("\(family)")

            for name in UIFont.fontNames(forFamilyName: family) {
                print("   \(name)")
            }
        }

Step : 3

Get the name of font from above snippet and after getting the name you can set the font name to your respected element as below

self.headerButton.titleLabel.font = [UIFont fontWithName:@"Nunito-Black" size:25];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download