AdrianGutierrez AdrianGutierrez - 2 months ago 134x
Swift Question

Add subtitle under the title in navigation bar controller in Xcode

So im 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 its in my viewDidLoad...

I tried this:

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

Its the only thing that wont show any errors but still doesnt work.. It literally does nothing. At least nothing visible at run time.

On a side note, swift is preferred. Thanks!


Though there is a solution but it has some known issues

Solution is writing a function like this

func setTitle(title:String, subtitle:String) -> UIView {
    let titleLabel = UILabel(frame: CGRectMake(0, -2, 0, 0))

    titleLabel.backgroundColor = UIColor.clearColor()
    titleLabel.textColor = UIColor.grayColor()
    titleLabel.font = UIFont.boldSystemFontOfSize(17)
    titleLabel.text = title

    let subtitleLabel = UILabel(frame: CGRectMake(0, 18, 0, 0))
    subtitleLabel.backgroundColor = UIColor.clearColor()
    subtitleLabel.textColor = UIColor.blackColor()
    subtitleLabel.font = UIFont.systemFontOfSize(12)
    subtitleLabel.text = subtitle

    let titleView = UIView(frame: CGRectMake(0, 0, max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), 30))

    let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width

    if widthDiff > 0 {
        var frame = titleLabel.frame
        frame.origin.x = widthDiff / 2
        titleLabel.frame = CGRectIntegral(frame)
    } else {
        var frame = subtitleLabel.frame
        frame.origin.x = abs(widthDiff) / 2
        titleLabel.frame = CGRectIntegral(frame)

    return titleView

Using this function for custom navigation title view in viewDidLoad

self.navigationItem.titleView = setTitle("Title", subtitle: "SubTitle")

Only known issue is that if subtitle becomes very large than the misplacement occurs.

Final Outcome enter image description here