0

Is there a way to query the total number of characters in a UIFont? For example, something like this: UIFont.systemFont(ofSize:16).count ? I am building an app to browse through all characters in a UIFont. I would like to know the total count of glyphs defined for that font, preferrably the maximum unicode code it supports.

andrewz
  • 4,729
  • 5
  • 49
  • 67
  • Do you mean to say the number of unicode and non-unicode characters that the font supports? – KrishnaCA Feb 12 '17 at 13:49
  • @KrishnaCA Yes. – andrewz Feb 12 '17 at 14:15
  • It can be done using `CTFont`. Please check my answer for details. – KrishnaCA Feb 12 '17 at 14:52
  • Note that you've switched your question half-way through. The number of characters in a font is not the same as the number of glyphs. There can be (and often are) more glyphs than characters. As a famous example from English, many fonts have a special glyph (called a ligature) for the sequence of characters "fi". There are many more examples, especially in other languages (Arabic has different glyphs for many letters depending on where it appears in the word). It sounds like @KrishnaCA's answer is what you mean, though. – Rob Napier Feb 12 '17 at 15:26
  • @RobNapier I am interested in the set of characters for which a font defines a glyph. I assume a character can be representable by a single UInt number. I am wondering if there is a way to determine from a UIFont object how many characters it can represent, and also preferably which characters. If I get to know the highest UInt number of its characters I can determine the limit of its character range. – andrewz Feb 12 '17 at 16:39

1 Answers1

3

I believe you can achieve that by the following way using CoreText:

import CoreText

extension CharacterSet {
   func charCount() -> Int {
       var count = 0
       for plane:UInt8 in 0...16 where self.hasMember(inPlane: plane) {
          for unicode in UInt32(plane) << 16 ..< UInt32(plane+1) << 16 {
              if let uniChar = UnicodeScalar(unicode) {
                  if self.contains(uniChar) {
                     count += 1
                  }
              }
          }
       }
       return count
   }
}

func getCountForFont(font: UIFont) -> Int {

    let coreFont: CTFont = font
    let characterSet: CharacterSet = CTFontCopyCharacterSet(coreFont) as CharacterSet
    let count = characterSet.charCount()
    return count
}
KrishnaCA
  • 5,615
  • 1
  • 21
  • 31