首页 > 解决方案 > iOS 自动使用自定义阿拉伯/西里尔字体

问题描述

我正在尝试了解是否可以使用自定义的阿拉伯文和西里尔文字体而无需switch/if-else对用户的语言设置进行操作。

我可以在应用程序中成功使用我的自定义字体。我想以同样的方式提供自定义 Ar/Cy 字体,我知道我可以将它构建到应用程序中。如果我有我的字体SpecialFont.otf并且还提供SpecialFont-CY.otf当用户使用西里尔语言时操作系统如何知道使用 SpecialFontCY.otf?理想情况下,操作系统将知道用户的主要字体,并且能够选择匹配/包含该语言正确字形的字体。

PS。这不是关于如何使用自定义字体的问题,我可以做到。我想知道如何为各种语言提供多种字体以完全支持世界,而无需编写如下代码:

if NSLocale.preferredLanguages.first == "Arabic"
   let myFont = UIFont(name:"SpecialFont-AR", size: 17)
else if NSLocale.preferredLanguages.first == "Russian"
   let myFont = UIFont(name:"SpecialFont-CY", size: 17)
...etc

标签: iosswiftxcodefontsinternationalization

解决方案


与其使用 UIFont,不如使用 UIFontDescriptor。有了它,您可以设置字体属性cascadeList,它告诉系统根据字形可用性选择字体的顺序(即查看 SpecialFont,但如果找不到 ب 字形,请尝试 SpecialFont-CY,然后是 SpecialFont-AR )。

级联列表的要点是为给定的字形选择正确的字体。这样,如果字符串包含混合在一起的西里尔文、阿拉伯文和拉丁文,它仍然可以正常工作。

例如:

// Start with your base font
let font = UIFont(name:"SpecialFont", size: 17)!

// Create the ordered cascade list.
let cascadeList = [
    UIFontDescriptor(fontAttributes: [.name: "SpecialFont-AR"]),
    UIFontDescriptor(fontAttributes: [.name: "SpecialFont-CY"]),
]

// Create a new font descriptor based on your existing font, but adding the cascade list
let cascadedFontDescriptor = font.fontDescriptor.addingAttributes([.cascadeList: cascadeList])

// Make a new font base on this descriptor
let cascadedFont = UIFont(descriptor: cascadedFontDescriptor, size: font.pointSize)

这在为全球受众创建应用程序(WWDC 2018) 中有详细介绍。


推荐阅读