Multiline Navigationbar Title

23,790

Solution 1

Here is a code example of how you can create a multiline navigationBar title

let label: UILabel = UILabel(frame: CGRectMake(0, 0, 400, 50))
label.backgroundColor = UIColor.clearColor()
label.numberOfLines = 2
label.font = UIFont.boldSystemFontOfSize(16.0)
label.textAlignment = .Center
label.textColor = UIColor.whiteColor()
label.text = "This is a\nmultiline string for the navBar"
self.navigationItem.titleView = label

Swift 5.x:

let label = UILabel()
label.backgroundColor = .clear
label.numberOfLines = 2
label.font = UIFont.boldSystemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = .white
label.text = "This is a\nmultiline string for the navBar"
self.navigationItem.titleView = label

Solution 2

This is doable in a storyboard. Just drag a UIView into the Navigation bar, then drag a UILabel onto it in the document outline, set lines to 2 and alignment to center.

enter image description here

Share:
23,790
Cody Harness
Author by

Cody Harness

Mobile developer for Android and iOS.

Updated on August 11, 2021

Comments

  • Cody Harness
    Cody Harness over 2 years

    I am trying to set the title label in my navigation bar to allow multiple lines. I have custom navigation controller code that I am placing the multiline code into. I know that the code already there works, but my multiline part is not working.

    let titleLabel = UILabel()
    titleLabel.frame = CGRectMake(0, 0, self.navigationBar.frame.width, self.navigationBar.frame.height * 2)
    titleLabel.numberOfLines = 0
    titleLabel.lineBreakMode = .ByWordWrapping
    
    navigationItem.titleView = titleLabel
    

    But the text still runs off at the end. I've also tried putting this into the individual view controller itself, adding self.navigationController?. in front of navigationItem with the same results.

    Is there something I'm missing in my code that would keep the title label from using multiple lines?

    • Cœur
      Cœur over 7 years
      Your navigationBar.frame.width was maybe not yet sized to fit the screen. You may want to override viewDidLayoutSubviews to detect the right frame.
  • Cody Harness
    Cody Harness over 8 years
    Gonna require some tweaking to get it to behave more like how I want it to, but this did help.
  • gutte
    gutte over 6 years
    I used navigationItem.titleView without setting the frame explicitly and it is working just fine.
  • Azharhussain Shaikh
    Azharhussain Shaikh over 5 years
    @Rashwan L if you are define the frame of UILabel it will lead to the label to the left align so just leave the frame part and use as just a "let label = UILabel()". and it will work perfect and set its own self in the center aligned.
  • David Homes
    David Homes about 3 years
    any hints on doing this in swiftui?
  • Paul Brewczynski
    Paul Brewczynski over 2 years
    Why width 400points?