我正在使用UIFont更改我的应用程序中的默认字体。代码在iOS 10及更低版本上工作正常,但它在iOS 11上返回nil,没有任何改变。我正在使用swift 4
这是我返回nil的代码:
UIFont(name: "AIranianSans", size: 20)
你可以帮帮我吗 ?怎么了 ?
尝试检查可用的字体
for familyName:String in UIFont.familyNames {
print("Family Name: \(familyName)")
for fontName:String in UIFont.fontNames(forFamilyName: familyName) {
print("--Font Name: \(fontName)")
}
}
可能是字体拼写不同。
https://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/在这里提到以下步骤之后,我无法在运行时在swift4中加载应用程序中的字体。当我们在故事板中应用特定的自定义字体时,字体将在运行时出现。然后只有这个API
UIFont(name: "font name", size: 20.0)
返回字体实例,否则它将仅返回nil。所以设计时自定义字体工作正常但不是运行时
要运行运行时我们需要加载字体
加载您喜欢的字体文件
UIFont.registerFontWithFilenameString(filenameString: "font 1 Sans LF Bold.ttf", bundle: Bundle.main)
UIFont.registerFontWithFilenameString(filenameString: "font 2Sans LF Light.ttf", bundle: Bundle.main)
UIFont.registerFontWithFilenameString(filenameString: "font 3Sans LF Regular.ttf", bundle: Bundle.main)
UIFont.registerFontWithFilenameString(filenameString: "font 4Sans LF Medium.ttf", bundle: Bundle.main)
public static func registerFontWithFilenameString(filenameString:String,bundle:Bundle){
guard let pathForResourceString = bundle.path(forResource: filenameString, ofType: nil) else {
print("UIFont+: Failed to register font - path for resource not found.")
return
}
guard let fontData = NSData(contentsOfFile: pathForResourceString) else {
print("UIFont+: Failed to register font - font data could not be loaded.")
return
}
guard let dataProvider = CGDataProvider(data: fontData) else {
print("UIFont+: Failed to register font - data provider could not be loaded.")
return
}
guard let fontRef = CGFont(dataProvider) else {
print("UIFont+: Failed to register font - font could not be loaded.")
return
}
var errorRef: Unmanaged<CFError>? = nil
if (CTFontManagerRegisterGraphicsFont(fontRef, &errorRef) == false) {
print("UIFont+: Failed to register font - register graphics font failed - this font may have already been registered in the main bundle.")
}