Search code examples
iosfontsnsattributedstring

Using fontello fonts in native iOS7 app


How would I go about taking a character from here: http://fontello.com/ and using it in a native iOS 7 application for use in UILabels or UITextViews?

Is this an appropirate use for NSAttributedString?

Anyone have any examples of doing this type of work?

thanks


Solution

  • This is fine, with or without NSAttributedString. You can apply NSFontNameAttribute to certain ranges, or you can just assign the font property on the UILabel. A custom font is no different than any other kind of font (sort of… more in a moment).

    So the basics. Create your font file. The piece you care about is the TTF (True Type Font). Copy it into your app, and make sure it's being copied in during the "Copy" phase. (It'll do that automatically if you just drop it into the app and add it to a target.)

    Add it to your Info pane for your target. It's the "Fonts provided by application" setting, and it's an array:

    enter image description here

    And then you can just load the font:

    self.label.font = [UIFont fontWithName:@"myfont" size:14.0];
    

    Keep in mind that the name in Info is the filename. The name in fontWithName:size: is the font name. They can be different, especially if you rename the file; that doesn't rename the font.

    Fontello will tell you the code for each glyph. If it says U+E800, you'd put that in an NSString as @"\ue800".

    You'll probably create fonts that don't have every character in them (this happens with built-in fonts too, but you don't usually notice it or worry about it). You can easily mix this stuff into "normal" text like:

    self.label.text = @"Hey! \uE800";
    

    If iOS can't find a character for H in your font, it'll fall back to the default font. You may want more control than that, so that you can mix and match from fonts and select just the right font for each character. If you want that kind of control, see Session 223: Using Fonts with Text Kit from WWDC 2013. Some of that is iOS 7-only. With iOS 6, you may have to use NSAttributedString and correctly set the font for each range.