Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all available characters from a font

Tags:

swift

fonts

I am developing an iOS app in Swift 3. In this app I am listing all available fonts (system provided) but I would like to list all available characters for them too.

For example I am using Font Awesome to and I want the user to be able to select any of the characters/symbols from a list. How can I do this?

This is how I get an array of the fonts. How can I get an array of all characters for a selected font?

UIFont.familyNames.map({ UIFont.fontNames(forFamilyName: $0)}).reduce([]) { $0 + $1 }
like image 582
Jonathan Clark Avatar asked Nov 23 '25 08:11

Jonathan Clark


1 Answers

For each UIFont, you have to get characterSet of that font. For example, I take first UIFont.

let firsttFont = UIFont.familyNames.first

let first = UIFont(name: firsttFont!, size: 14)
let fontDescriptor = first!.fontDescriptor
let characterSet : NSCharacterSet = fontDescriptor.object(forKey: UIFontDescriptorCharacterSetAttribute) as! NSCharacterSet

Then, use this extension to get all characters of that NSCharacterSet:

extension NSCharacterSet {
    var characters:[String] {
        var chars = [String]()
        for plane:UInt8 in 0...16 {
            if self.hasMemberInPlane(plane) {
                let p0 = UInt32(plane) << 16
                let p1 = (UInt32(plane) + 1) << 16
                for c:UTF32Char in p0..<p1 {
                    if self.longCharacterIsMember(c) {
                        var c1 = c.littleEndian
                        let s = NSString(bytes: &c1, length: 4, encoding: String.Encoding.utf32LittleEndian.rawValue)!
                        chars.append(String(s))
                    }
                }
            }
        }
        return chars
    }
}

(Ref: NSArray from NSCharacterset)

So, at last, just call characterSet.characters to get all characters (in String)

like image 124
Duyen-Hoa Avatar answered Nov 24 '25 23:11

Duyen-Hoa