Search code examples
iosiphoneswiftuinavigationbartitlebar

NavigationBar title doesn't appear


I add NavigationBar programmatically and later added title to it, but it doesn't appear at all. What is the problem here?

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 appears, but title not. How to fix it?

I've tried this too:

navigationBar.topItem?.title = "BBB"

nothing again


Solution

  • Hope this will help you out.

    // 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)
    

    This code is working for me.

    UPDATE : 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)