NavigationBar标题未显示

时间:2015-10-07 09:40:34

标签: ios iphone swift uinavigationbar titlebar

我以编程方式添加NavigationBar,后来又添加了标题,但它根本没有出现。这有什么问题?

let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 55))
navigationBar.barTintColor = UIColor(red: 44/255, green: 54/255, blue: 63/255, alpha: 1)
navigationController?.navigationItem.title = "AAA"
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
view.addSubview(navigationBar)
出现

navigationBar,但标题不是。如何解决?

我也试过这个:

navigationBar.topItem?.title = "BBB"

再一次

2 个答案:

答案 0 :(得分:8)

希望这会帮助你。

// Create the navigation bar
let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 64)) 

// Offset by 20 pixels vertically to take the status bar into account

navigationBar.backgroundColor = UIColor.whiteColor()

// Create a navigation item with a title
let navigationItem = UINavigationItem()
    navigationItem.title = "Title"

// Assign the navigation item to the navigation bar
navigationBar.items = [navigationItem]

// Make the navigation bar a subview of the current view controller
self.view.addSubview(navigationBar)

这段代码对我有用。

更新:Swift 4 / Swift 5

// Create the navigation bar
let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 64))

// Offset by 20 pixels vertically to take the status bar into account

navigationBar.backgroundColor = UIColor.white

// Create a navigation item with a title
let navigationItem = UINavigationItem()
navigationItem.title = "Title"

// Assign the navigation item to the navigation bar
navigationBar.items = [navigationItem]

// Make the navigation bar a subview of the current view controller
self.view.addSubview(navigationBar)

答案 1 :(得分:0)

导航栏标题在显示的视图控制器中设置。通常这是在视图中完成加载视图控制器:

override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "AAA"
}

编辑:在意识到OP正在将UINavigationBar添加到UIViewController而未使用标准UINavigationController之后:

let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 55))
navigationBar.barTintColor = UIColor(red: 44/255, green: 54/255, blue: 63/255, alpha: 1)
let navigationItem = UINavigationItem.init(title: "AAA")
navigationBar.items = [navigationItem]
view.addSubview(navigationBar)