Search code examples
iosxamarincustom-renderer

How to display a label with small caps font style in Xamarin Forms iOS?


My designer for our Xamarin Forms app specified Small Caps for a label field. There are several discussions on how to do this in Xamarin for Android, but I can't find anything for iOS.

I know I will need a custom renderer and have found a good discussion here, but am being challenged in converting the Swift code in that article to C# for Xamarin iOS.

Here's that code:

let systemFont = UIFont.systemFont(ofSize: 24.0, weight: UIFontWeightLight)
let smallCapsDesc = systemFont.fontDescriptor.addingAttributes([
    UIFontDescriptorFeatureSettingsAttribute: [
        [
            UIFontFeatureTypeIdentifierKey: kUpperCaseType,
            UIFontFeatureSelectorIdentifierKey: kUpperCaseSmallCapsSelector
        ]
    ]
])
let font = UIFont(descriptor: smallCapsDesc, size: systemFont.pointSize)

I know that I will put something into my OnElementChanged method, but the FontDescriptor does not have an addingAttributes method or an Attributes collection, so am challenged in adding additional properties.


Solution

  • the FontDescriptor does not have an addingAttributes method or an Attributes collection

    You are looking for the UIFont.FontDescriptor.CreateWithAttributes method.

    Example:

    var systemFont = UIFont.SystemFontOfSize(24, UIFontWeight.Light);
    var attributes = new UIFontAttributes(
        new UIFontFeature(CTFontFeatureUpperCase.Selector.UpperCaseSmallCaps),
        new UIFontFeature(CTFontFeatureLowerCase.Selector.LowerCaseSmallCaps)
    );
    var smallCapsDesc = systemFont.FontDescriptor.CreateWithAttributes(attributes);
    var font = UIFont.FromDescriptor(smallCapsDesc, systemFont.PointSize);