Search code examples
swiftnsattributedstringswift2xcode7

attributed text not working with custom font in xcode 7


I am using Xcode 7. When using attributed text with custom font it displays in the storyboard but is not working on the device. I tried the following code:

var myMutableString = NSMutableAttributedString()

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 8
    paragraphStyle.alignment = NSTextAlignment.Center

    myMutableString = NSMutableAttributedString(string: "\"Taking out my shorts and T-Shirt a night before has helped create a great morning routine for my walk\"", attributes: [NSFontAttributeName:UIFont(name: "Gotham Medium", size: 20.0)!])
    myMutableString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, myMutableString.length))

    quotesLabel.attributedText = myMutableString

Solution

  • Make sure that your app contains the font file for Gotham Medium. Check out this great article about Common Mistakes With Adding Custom Fonts in iOS Apps.

    1. Include your fonts in your XCode project
    2. Make sure that they’re included in the target
    3. Double check that your fonts are included as Resources in your bundle
    4. Include your iOS custom fonts in your application plist
    5. Find the name of the font
    6. Use UIFont and specify the name of the font