以编程方式在Swift中设置tabBarItem标题

我有四个UIViewControllers链接到UITabBarController的标签栏。 我需要将标签栏项目标题设置在故事板以外,并在其类中。

我试过了..

class MyViewController: UIViewController { required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.title = NSLocalizedString(MyConstants.StringKeys.TabName, tableName: Constants.Strings.MyTable, comment: Constants.EmptyString); } } 

这被称为,但标题从未设置。 同self.tabBarItem.title =“标题”

我也尝试在viewDidLoad中设置标题,但只是在去视图控制器后更新标题。

思考?

您可以通过设置视图控制器的title属性在viewDidLoad设置视图控制器本身的选项卡标题。

 title = "Number 0" 

或者,如果要设置标签栏控制器中的标题,可以在标签栏控制器的viewDidLoad像这样设置它们:

 tabBar.items?[0].title = "Number 0" tabBar.items?[1].title = "Number 1" 

我想通了,看起来像是由awakeFromNib()写的。

 override func awakeFromNib() { super.awakeFromNib() self.title = NSLocalizedString(MyConstants.StringKeys.TabName, tableName: Constants.Strings.MyTable, comment: Constants.EmptyString); } 

我把我的self.title作业移到那里,它纠正了我的问题。

这里是每个viewController.swift文件中的解决scheme,你可以添加下面的代码

  override func awakeFromNib() { self.tabBarItem.title = "title" self.tabBarItem.image = "image.png" } 

这是一个超级简单的awakeFromNib方法,当nib创build简单的时候,你可以很容易地调用任何东西,因为在ViewDidLoad或者你点击或者select时调用的任何viewControllerDelegate方法。 所以这是一个超级简单的function。

谢谢。

我一直在尝试不同的解决scheme,但唯一的解决scheme是在UITabBarControllerviewWillAppear方法中添加标签栏。 我不会在每个视图控制器中单独执行它,因为它仅在按下标签栏button时才起作用:

 override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let items = tabBar.items else { return } items[0].title = "Title0" items[1].title = "Title1" items[2].title = "Title2" items[3].title = "Title3" }