自定义字体在swift中变成零值3

问题描述:

我想将属性字符串设置为我的UILabel。所以我以这种方式定义了属性。自定义字体在swift中变成零值3

let attribute1:[String:Any]=[ 
     NSForegroundColorAttributeName: UIColor.init(colorLiteralRed: 120.0/255, green: 173.0/255, blue: 194.0/255, alpha: 1.0), 
     NSFontAttributeName:UIFont.init(name: "Bariol_Bold", size: 15.0)!] 
let attributedStringGreeting=NSAttributedString.init(string: welcomeMessage, attributes: attribute1) 

但我在该行收到此错误:

NSFontAttributeName:UIFont.init(name: "Bariol_Bold", size: 15.0)!] 

这是否意味着我的自定义字体未服用?但是当我从IB中设置字体时,它会显示出来。

fatal error: unexpectedly found nil while unwrapping an Optional value

我该如何解决这个问题?请帮帮我。

enter image description here

enter image description here

+0

您可以将其解释为“找不到字体”。你确定它实际上被命名为“Bariol_Bold”吗?您需要输入* exact *名称才能使用。另外请确保您已正确导入字体文件。 – LinusGeffarth

+2

尝试使用'Bariol-Bold' –

+0

您是否添加了构建阶段 - >复制包资源 – Bala

试试这个

let attribute1:[String:Any] = [NSFontAttributeName: UIFont(name: "Bariol-Bold", size: 18)! , 
       NSForegroundColorAttributeName : UIColor.init(colorLiteralRed: 120.0/255, green: 173.0/255, blue: 194.0/255, alpha: 1.0)] 

    let attributedStringGreeting=NSAttributedString.init(string: welcomeMessage, attributes: attribute1) 

如果实际的字体名称不相同的文件名,这样的事情是如何找到字体名称经常会发生冲突。

采取这种措施,

  1. 添加的所有字体文件在你的包
  2. 将所有字体文件的列表中下关键的的info.plist:“字体提供通过应用”
  3. 现在运行下面的代码,

    for fontFamilyName in UIFont.familyNames{ 
        for fontName in UIFont.fontNames(forFamilyName: fontFamilyName){ 
         print("Family: \(fontFamilyName)  Font: \(fontName)" 
        } 
    } 
    
  4. 现在看到你的控制台的输出,所有可用的字体打印在这里,检查实际您提供的字体的字体名称,只需找到“bariol”即可。

  5. 现在,使用该字体名称UIFont.init(name: "Actual Font name comes here", size: 15.0)!]

的问题是在名称中。每次没有必要文件名和字体名称是相似的。要知道确切的字体名称,您可以使用以下功能。

func printMyFonts() { 
    print("--------- Available Font names ----------") 
    for name in UIFont.familyNames { 
     print(name) 
     print(UIFont.fontNames(forFamilyName: name)) 
    } 
} 

希望这有助于!