如何调整UITabBarController的标题文本字体大小?

时间:2019-06-26 05:24:13

标签: swift uitabbarcontroller

我正在使用UITabBarController,但是我只有2个标签。我只想使用文本,而不是使用图标。我创建了一个酒吧项目标题,但是文本很小,并且很难修改它。我怎样才能使一个条形项目只是适合该部分的文本?

我试图以编程方式更改字体大小,但我还很新,很快就遇到了麻烦。

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        UITabBar.appearance().tintColor = .white
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)

        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.lightGray], for: .normal)


        return true
    }
}

3 个答案:

答案 0 :(得分:0)

UITextAttributeFont在iOS 7中已弃用。您应该改用NS变体:

import UIKit

let appearance = UITabBarItem.appearance()
let attributes = [NSAttributedStringKey.font:UIFont(name: "Your font style", size: 20)]
appearance.setTitleTextAttributes(attributes as [NSAttributedStringKey : Any], for: .normal)

答案 1 :(得分:0)

对于UIViewController中的每个UITabBarController,请调用setTitleTextAttributes(_:for:)中控制器的tabBarItem上的viewDidLoad(),即

class VC1: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBarItem.setTitleTextAttributes([.font: UIFont.systemFont(ofSize: 20.0, weight: .regular)], for: .normal)

    }
}

class VC2: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBarItem.setTitleTextAttributes([.font: UIFont.systemFont(ofSize: 20.0, weight: .regular)], for: .normal)
    }
}

编辑:

自从您在controllers中创建了tabBarController的{​​{1}}以来,这里就是如何使之工作的方法。

子类storyboard并设置其UITabBarController tabBarItem titleTextAttributes viewDidLoad()`的viewControllers``,即

in

现在将class TabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() self.viewControllers?.forEach({ $0.tabBarItem.setTitleTextAttributes([.font: UIFont.systemFont(ofSize: 20.0, weight: .regular)], for: .normal) }) } } TabBarController的{​​{1}}设置为class

我希望这能解决您的问题。

答案 2 :(得分:0)

UITabBarItem.appearance()。setTitleTextAttributes([NSAttributedString.Key.font:UIFont(name:“ FontName”,size:10)!],用于:.normal) UITabBarItem.appearance()。setTitleTextAttributes([NSAttributedString.Key.font:UIFont(name:“ FontName”,size:10)!],用于:.selected)