swift 更改标签栏标题字体

swift change tab bar title font

我想知道如何在使用标签栏时更改标签中标题的字体和大小。

我查看了文档,但找不到有关标题字体和大小的任何信息 - source

您可以通过外观代理更改它:

let font: UIFont = ...
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: font], forState: .Normal)

Swift 4:

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: font], for: .normal)

你应该把这个放在你的应用委托中 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool

更新 swift 3.

将其放入 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool

中的应用委托中
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: yourFont], for: .normal)

Swift 4.1

UITabBarItem.appearance().setTitleTextAttributes([kCTFontAttributeName as NSAttributedStringKey: font], for: .normal)

我发现这个 Swift 5 解决方案很有用:

UITabBarItem.appearance().setTitleTextAttributes([.font: UIFont(name: "FontName", size: 10)!], for: .normal)

Swift 5.5

let font: UIFont = UIFont(font: "arial", size: 15)! UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)

就我而言,此解决方案对我有用 (Swift 5.5):

let fontSize: CGFloat = 12
      
if #available(iOS 13, *) {
    let appearance = tabBarController.tabBar.standardAppearance
    appearance.stackedLayoutAppearance.normal.titleTextAttributes = [
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize, weight: .medium)
    ]
    appearance.stackedLayoutAppearance.selected.titleTextAttributes = [
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize, weight: .medium)
    ]
} else {
     if #available(iOS 11, *) {
         UITabBarItem.appearance().setTitleTextAttributes([
             NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize, weight: .medium)
         ], for: .normal)
         UITabBarItem.appearance().setTitleTextAttributes([
             NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize, weight: .medium)
         ], for: .selected)
     }
}