user4809833
user4809833

Reputation:

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

Upvotes: 4

Views: 5116

Answers (2)

iGatiTech
iGatiTech

Reputation: 2268

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)

Upvotes: 8

Abhinav
Abhinav

Reputation: 38172

Navigation bar title is set in the view controller being displayed. Normally this is done in view did load on the view controller:

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

EDIT: After realising that OP is adding UINavigationBar on to UIViewController and not using standard 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)

Upvotes: 0

Related Questions