Download font .ttf file from web and store on iPhone

后端 未结 5 614
余生分开走
余生分开走 2020-12-18 11:39

Is it possible to download .ttf file from web and store it on iPhone. Then use that for for labels and all other stuff ? Because my client want to control fonts from databas

5条回答
  •  忘掉有多难
    2020-12-18 12:02

    Swift 4 solution by extension:

    extension UIFont {
    
        /**
         A convenient function to create a custom font with downloaded data.
    
         - Parameter data: The local data from the font file.
         - Parameter size: Desired size of the custom font.
    
         - Returns: A custom font from the data. `nil` if failure.
    
         */
        class func font(withData data: Data, size: CGFloat) -> UIFont? {
    
            // Convert Data to NSData for convenient conversion.
            let nsData = NSData(data: data)
    
            // Convert to CFData and prepare data provider.
            guard let cfData = CFDataCreate(kCFAllocatorDefault, nsData.bytes.assumingMemoryBound(to: UInt8.self), nsData.length),
                let dataProvider = CGDataProvider(data: cfData),
                let cgFont = CGFont(dataProvider) else {
                print("Failed to convert data to CGFont.")
                return nil
            }
    
            // Register the font and create UIFont.
            var error: Unmanaged?
            CTFontManagerRegisterGraphicsFont(cgFont, &error)
            if let fontName = cgFont.postScriptName,
                let customFont = UIFont(name: String(fontName), size: size) {
                return customFont
            } else {
                print("Error loading Font with error: \(String(describing: error))")
                return nil
            }
    
        }
    }
    

    Usage:

    let customFont = UIFont.font(withData: data, size: 15.0)
    

提交回复
热议问题