如何在ViewController的顶部设置标题

时间:2018-01-22 19:55:44

标签: ios swift cocoa-touch

在我的应用程序中,我有一个tabBarViewController,这是第一个栏:

class FirstViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.white
  }

  override func viewWillAppear(_ animated: Bool) {
    self.navigationItem.title = "RECENTS"
  }

}

这是自定义类:

class CustomTabBar: UITabBarController {

  override func viewDidLoad() {
    super.viewDidLoad()

    let firstVC = FirstViewController()
    let secondVC = SecondViewController()
    let thirdVC = ThirdViewController()

    firstVC.tabBarItem.title = "RECENT"
    secondVC.tabBarItem.title = "MAP"
    thirdVC.tabBarItem.title = "SETTINGS"

    firstVC.title = "RECENT"
    secondVC.title = "MAP"
    thirdVC.title = "SETTINGS"

    viewControllers = [firstVC,secondVC,thirdVC]
  }

}

所以我的问题是:如何将标题放在视图控制器的顶部? 在之前的代码中我尝试过,但它不起作用!

这样的事情: enter image description here

2 个答案:

答案 0 :(得分:2)

当视图控制器包含在title中时,会显示UINavigationController属性。这里有一些代码替换了你的例子中的最后一行(即viewControllers赋值),应该可以解决这个问题:

let firstNC = UINavigationController(rootViewController: firstVC)
let secondNC = UINavigationController(rootViewController: secondVC)
let thirdNC = UINavigationController(rootViewController: thirdVC)
viewControllers = [firstNC,secondNC,thirdNC]

答案 1 :(得分:1)

override func viewWillAppear(animated: Bool) {
   super.viewWillAppear(animated)
   self.tabBarController?.navigationItem.title = "My Title"
}

这应该有效。我希望它可以帮助你。

或者你可以试试这个。

let vc3 = UINavigationController(rootViewController: SearchVC())
vc3.tabBarItem.image = UIImage(named: "vyhledavani")
vc3.title = "Vyhledat"
vc3.tabBarItem.tag = 2
viewControllers = [vc3, ...]