Add subtitle under the title in navigation bar controller in Xcode

AdrianGutierrez picture AdrianGutierrez · Jul 28, 2016 · Viewed 26.9k times · Source

So I'm wanting to add a "subtitle" under the title in the navigation bar in navigation controller.

Mostly everything I look up so far wants me to use CGRect. I don't know a whole lot what that is and it sounds like its wanting me to create an entire new view which is not what I am wanting to do.

My question is, is there a dot method to adding a subtitle view easily?

The closest thing I found was posted on stack overflow and here is the link:

Create a subtitle in navigationbar

Apparently last year this worked but now I am getting errors and it's in my viewDidLoad...

I tried this:

self.navigationController?.navigationItem.prompt = "Subtitle Here"

It's the only thing that won't show any errors but still doesn't work. It literally does nothing. At least nothing visible at run time.

On a side note, swift is preferred. Thanks!

Answer

user2325031 picture user2325031 · Feb 22, 2017

Here is my version using a stack view on an extension.

extension UINavigationItem {



     func setTitle(title:String, subtitle:String) {

            let one = UILabel()
            one.text = title
            one.font = UIFont.systemFont(ofSize: 17)
            one.sizeToFit()

            let two = UILabel()
            two.text = subtitle
            two.font = UIFont.systemFont(ofSize: 12)
            two.textAlignment = .center
            two.sizeToFit()



            let stackView = UIStackView(arrangedSubviews: [one, two])
            stackView.distribution = .equalCentering
            stackView.axis = .vertical
            stackView.alignment = .center

            let width = max(one.frame.size.width, two.frame.size.width)
            stackView.frame = CGRect(x: 0, y: 0, width: width, height: 35)

            one.sizeToFit()
            two.sizeToFit()



            self.titleView = stackView
        }
    }