Search code examples
swiftnavbartitleios11xcode9

How to line break long large title in iOS 11?


I am trying to use the new large title system in iOS 11 using Swift. When the title gets too long (see image example), it adds ... instead of line breaking or shrinking the text size. How can I add a line break?

Example image with long title

Here is some of the code I'm using to set up the title:

self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationController?.navigationBar.largeTitleTextAttributes = [NSForegroundColorAttributeName: MyGlobalVariable.themeMainColor]
self.navigationController?.navigationBar.largeTitleTextAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 22)]
navigationItem.title = "Search by Name"

Solution

  • Try this:

    for navItem in (self.navigationController?.navigationBar.subviews)! {
        for itemSubView in navItem.subviews {
            if let largeLabel = itemSubView as? UILabel {
                largeLabel.text = self.title
                largeLabel.numberOfLines = 0
                largeLabel.lineBreakMode = .byWordWrapping
            }
        }
    }
    

    It worked for me.

    enter image description here