簡體   English   中英

如何以編程方式訪問iOS系統字體

[英]How to access the iOS system font programmatically

我正在嘗試更改導航欄標題的字體大小。 我知道我可以使用以下方法設置其屬性:

var attributes = [ NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont(name: "the font name", size: 18)! ]

...

 self.navigationController?.navigationBar.titleTextAttributes = attributes

我似乎找不到正確的“系統”字體名稱。

我追求的是默認的,也就是系統,字體名稱。 我嘗試打印所有可用的字體,結果發現它不屬於一個系列,並且似乎沒有明確的名稱。

我認為你需要:

NSFontAttributeName : UIFont.systemFontOfSize(19.0)

或者粗體版本:

NSFontAttributeName : UIFont.boldSystemFontOfSize(19.0)

有關用戶界面指南和字體的更多信息,請參閱本指南

您可以像這樣訪問系統字體,甚至可以設置字體的粗細:

對於字體粗細,您可以在這些常量之間進行選擇,可從iOS 8.2 獲得

UIFontWeightUltraLight,
UIFontWeightThin,
UIFontWeightLight,
UIFontWeightRegular,
UIFontWeightMedium,
UIFontWeightSemibold,
UIFontWeightBold,
UIFontWeightHeavy,
UIFontWeightBlack

SWIFT 4+:更短的版本

UIFont.systemFont(ofSize: 14.0, weight: .regular)

(與 Philippe 對最新版本的回答一致)

  • 斯威夫特 4

    UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.light)

除了所有答案之外,最好將系統字體與系統樣式一起使用,而不是定義自定義大小和粗細。 要以編程方式訪問它們,例如標題,您可以使用以下方法:

let font = UIFont.preferredFont(forTextStyle: .headline)

我知道至少對於 Swift 5 來​​說這是一個有效的代碼。

self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName : UIFont.systemFontOfSize(6)]

只需使用 UIFont (swift) 的方法:

let sysFont: UIFont = UIFont.systemFontOfSize(UIFont.systemFontSize())

希望能幫助到你!

試試下面的代碼:

self.navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name:"Arial", size:14.0)!, NSForegroundColorAttributeName:UIColor.blackColor()]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM