-1

I'm trying to use a font that has small caps. I found a UIFont extension on some guy's website that claimed it would do small caps but alas, no luck. Any ideas?

extension UIFont {

  func smallCapsFontVariant(smallCapsForUppercase: Bool = true) -> UIFont {
  var features = [
  [UIFontFeatureTypeIdentifierKey: kLowerCaseType,
    UIFontFeatureSelectorIdentifierKey: kLowerCaseSmallCapsSelector]
]

if smallCapsForUppercase {
  features.append([UIFontFeatureTypeIdentifierKey: kUpperCaseType,
    UIFontFeatureSelectorIdentifierKey: kUpperCaseSmallCapsSelector])
}

let smallCapsFontDescriptor = fontDescriptor().fontDescriptorByAddingAttributes([
  UIFontDescriptorFeatureSettingsAttribute : features
  ])

return UIFont(descriptor: smallCapsFontDescriptor, size: 0d)
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
36 By Design
  • 3,203
  • 3
  • 18
  • 18
  • 5
    @LeoNatan I understand that, but users can tag questions with the language *they want an answer in*. The question doesn't have to be *about* the tagged language. For example, here, I know for a fact the OP doesn't want an answer in Objective-C. – Eric Aya Apr 15 '16 at 14:46

1 Answers1

2

The problem is that very few fonts have a small caps variant. If you're not using one of those few, you won't get small caps. You can't magically create a feature that isn't there...

Here's code that accesses the small caps variant of Didot:

    let desc = UIFontDescriptor(name:"Didot", size:18)
    let d = [
        UIFontFeatureTypeIdentifierKey:kLetterCaseType,
        UIFontFeatureSelectorIdentifierKey:kSmallCapsSelector
    ]
    let desc2 = desc.fontDescriptorByAddingAttributes(
        [UIFontDescriptorFeatureSettingsAttribute:[d]]
    )
    let f = UIFont(descriptor: desc2, size: 0)

Now f is the small caps variant of Didot, and you can use it in your interface.

If the font you're using is not Didot, then substitute it in that code; but be very sure to begin with that your font has a small caps variant, or this won't work.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Downvoting this answer seems silly, since it is demonstrably correct. – matt Apr 15 '16 at 17:05
  • This doesn't seem to work anymore. Possibly an iOS 9 issue? – nathan Jun 22 '16 at 05:30
  • @ntesler works fine in iOS 9, 10, whatever. Downloadable working project here: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch10p499fontDescriptor2/ch23p670font1dynamicType/ViewController.swift – matt Jun 22 '16 at 12:32
  • Ah thankyou! Didn't put the feature dictionary into an array – nathan Jun 23 '16 at 03:02