我正在使用UITabBarController
但我只有 2 个选项卡。我只想使用文本,而不是使用图标。我创建了一个条形图项目标题,但文本非常小,我很难修改它。如何使条形图项目仅包含合理适合该部分的文本?
我尝试以编程方式更改字体大小,但我对 swift 相当陌生,并且正在苦苦挣扎。
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
}
}
对于UITabBarController
中的每个UIViewController
,在控制器的tabBarItem
上调用setTitleTextAttributes(_:for:)
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)
}
}
编辑:
由于您已经在storyboard
中创建了tabBarController
controllers
,以下是您可以使其工作的方法。
子类UITabBarController
并将其viewControllers``
选项卡项in
viewDidLoad()' 的titleTextAttributes
,即
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
设置为storyboard
中UITabBarController
的class
。
我希望这将解决您的问题。
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)
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)