更改Swift中的标签栏字体

问题描述 投票:21回答:6

我一直在尝试更改标签栏项目的字体,但是我找不到任何Swift示例。我知道这就是你在Objective-C中改变它的方式:

[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont, nil] forState:UIControlStateNormal];

但是我怎么能把它翻译成Swift呢?

swift uitabbar uifont
6个回答
49
投票

在iOS 7中不推荐使用UITextAttributeFont。您应该使用NS变体:

import UIKit

let appearance = UITabBarItem.appearance()
let attributes = [NSFontAttributeName:UIFont(name: "American Typewriter", size: 20)]
appearance.setTitleTextAttributes(attributes, forState: .Normal)

31
投票

Swift 4.2

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

斯威夫特4

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

斯威夫特3

UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Font-Name", size: 10)!], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Font-Name", size: 10)!], for: .selected)

注意:对setTitleTextAttributes.normal使用.selected以使更改持续选择状态更改。


7
投票

把它放在didFinishLaunchingWithOptions下:

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

这适用于Swift 4


4
投票

另外@ Mc.Lover的回答,如果你想对应用程序中的所有标签栏项目进行更改,我建议在AppDelegate类的application函数中添加代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    //Just add this line to get it done.       
    UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "IranSansMobile", size: 15)!], for: UIControlState.normal)

    return true
}

2
投票

在Swift4版本中,您可以使用属性键来设置字体和前景色

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor(hexString: "#D8FFE8"), NSAttributedStringKey.font : UIFont(name: "HelveticaNeue-Bold", size: 16) as Any], for: .normal)
    UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor(hexString: "#FFFFFF"),NSAttributedStringKey.font : UIFont(name: "HelveticaNeue-Bold", size: 16) as Any], for: .selected)

2
投票

Swift 4.2

    UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "BahijTheSansArabic-Plain", size: 10)!], for: .normal)
    UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "BahijTheSansArabic-Plain", size: 10)!], for: .selected)
© www.soinside.com 2019 - 2024. All rights reserved.