2017-05-31 36 views
0

我想將屬性字符串設置爲我的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

回答

1

試試這個

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) 
2

如果實際的字體名稱不相同的文件名,這樣的事情是如何找到字體名稱經常會發生衝突。

採取這種措施,

  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)!]

3

的問題是在名稱中。每次沒有必要文件名和字體名稱是相似的。要知道確切的字體名稱,您可以使用以下功能。

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

希望這有助於!