Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 set custom font programmatically

Tags:

swift

How to set Custom font to UILabel or Any Other UIView programmatically (if it is possible) i know how to do it in storyboard but not programmatically thank you

this what i did enter image description here

like image 840
Hakim Douib Avatar asked Jun 21 '18 22:06

Hakim Douib


People also ask

How do I add custom fonts to Swift 4?

Add this by drag and drop to your files on the left side of the project. Add your CUSTOM fonts to the info. plist file. Make sure that you've linked all custom fonts you need: "Build Phases" -> "Copy Bundle Resources" -> "+" add your font.

How do I change the font style in Swift?

To change the font or the size of a UILabel in a Storyboard or . XIB file, open it in the interface builder. Select the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.


3 Answers

You can try

lbl.font = UIFont(name:"FontAwesome",size:15)

the name should be the font name as it is when you install it . not as the file name in your case was Noto Kufi Arabic instead of NotoKufiArabicRegular

click the font and open it with Font Book , then install it after that specify exactly the name shown in the parameter in the line above

like image 67
Sh_Khan Avatar answered Oct 12 '22 22:10

Sh_Khan


import Foundation
import UIKit

extension UIFont {

    public enum OpenSansType: String {
        case extraboldItalic = "-ExtraboldItalic"
        case semiboldItalic = "-SemiboldItalic"
        case semibold = "-Semibold"
        case regular = ""
        case lightItalic = "Light-Italic"
        case light = "-Light"
        case italic = "-Italic"
        case extraBold = "-Extrabold"
        case boldItalic = "-BoldItalic"
        case bold = "-Bold"
    }

    static func OpenSans(_ type: OpenSansType = .regular, size: CGFloat = UIFont.systemFontSize) -> UIFont {
        return UIFont(name: "OpenSans\(type.rawValue)", size: size)!
    }

    var isBold: Bool {
        return fontDescriptor.symbolicTraits.contains(.traitBold)
    }

    var isItalic: Bool {
        return fontDescriptor.symbolicTraits.contains(.traitItalic)
    }

}

Use:

self.numberLabel.font = UIFont.OpenSans(.bold, size: 20)
like image 45
Mohammad Razipour Avatar answered Oct 13 '22 00:10

Mohammad Razipour


If the previous answer doesn't help, you didn't configure all links correctly at xCode for sure!

  1. Add this by drag and drop to your files on the left side of the project.
  2. Add your CUSTOM fonts to the info.plist file.
  3. Make sure that you've linked all custom fonts you need: "Build Phases" -> "Copy Bundle Resources" -> "+" add your font.

More information you can get here: Medium.com

like image 24
J A S K I E R Avatar answered Oct 13 '22 00:10

J A S K I E R