嗨,我有这个代码而且它不起作用,我做错了什么?
- (void)viewDidLoad
{
[self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont, nil] forState:UIControlStateDisabled];
}
BTW,这不是我的viewDidLoad中唯一的东西,但我只是想告诉你那些我把它放在哪里。
答案 0 :(得分:65)
根据:How to change the Color of text in UITabBarItem in iOS 5
看起来解决方案可能是将消息发送到外观代理,而不是一个项目:
(在iOS 7.0 +中不推荐使用)
[[UITabBarItem appearance] setTitleTextAttributes:@{UITextAttributeFont: [UIFont fontWithName:@"AmericanTypewriter" size:20.0f]} forState:UIControlStateNormal];
对于iOS 7.0+,请使用:
[[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"AmericanTypewriter" size:20.0f]} forState:UIControlStateNormal];
答案 1 :(得分:9)
快速的方式,对于懒惰:
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(10)], forState: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(10)], forState: .selected)
答案 2 :(得分:2)
Swift 3
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "OpenSans", size: 10)!], for: .normal)
答案 3 :(得分:2)
Swift 4.1和自定义字体
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "Montserrat-Medium", size: 11)], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "Montserrat-Medium", size: 11)], for: .selected)
答案 4 :(得分:1)
雨燕4
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.tabbar], for: .normal)
答案 5 :(得分:0)
如果我在 viewDidLoad() 中添加了代码,那么在选择标签栏时我永远无法更改字体。
这是一篇很棒的文章,详细解释了如何做到这一点:HolySwift Article
简而言之,您需要在标签栏控制器中添加以下代码:
override var selectedIndex: Int {
didSet {
guard let selectedViewController = viewControllers?[selectedIndex] else {
return
}
selectedViewController.tabBarItem.setTitleTextAttributes([.font: UIFont.boldSystemFont(ofSize: 13)], for: .normal)
}
}
还有这个:
override var selectedViewController: UIViewController? {
didSet {
guard let viewControllers = viewControllers else {
return
}
for viewController in viewControllers {
if viewController == selectedViewController {
viewController.tabBarItem.setTitleTextAttributes([.font: UIFont.boldSystemFont(ofSize: 13)], for: .normal)
} else {
viewController.tabBarItem.setTitleTextAttributes([.font: UIFont.systemFont(ofSize: 12)], for: .normal)
}
}
}
}
PS:这也适用于自定义字体。