38

嗨,我有这个代码,但它不起作用,我做错了什么?

- (void)viewDidLoad
{    
    [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont, nil] forState:UIControlStateDisabled];
}

顺便说一句,这不是我 viewDidLoad 中唯一的东西,但我只是想向你们展示我放它的地方。

4

6 回答 6

73

根据:如何在 iOS 5 中更改 UITabBarItem 中文本的颜色

看起来解决方案可能会将消息发送到外观代理,而不是一项:

(在 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];
于 2012-06-17T07:00:01.283 回答
17

快速的方式,对于懒惰的人:

UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(10)], forState: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(10)], forState: .selected)
于 2016-06-21T07:31:52.863 回答
11

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)
于 2018-11-29T06:54:02.420 回答
4

斯威夫特 3

UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "OpenSans", size: 10)!], for: .normal)
于 2017-03-10T13:48:15.200 回答
3

斯威夫特 4

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.tabbar], for: .normal)
于 2018-10-01T13:11:06.950 回答
0

如果我在 viewDidLoad() 中添加了代码,那么在选择标签栏时我永远无法更改字体。

这是一篇很棒的文章,它解释了如何更详细地做到这一点:HolySwift 文章

简而言之,您需要在标签栏控制器中添加以下代码:

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:这也适用于自定义字体。

于 2021-06-30T09:37:56.243 回答