How to resize Title in a navigation bar dynamically

24,955

Solution 1

Used the below code in ViewDidload .

Objective C

self.title = @"Your TiTle Text";
UILabel* tlabel=[[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 40)];
tlabel.text=self.navigationItem.title;
tlabel.textColor=[UIColor whiteColor];
tlabel.font = [UIFont fontWithName:@"Helvetica-Bold" size: 30.0];
tlabel.backgroundColor =[UIColor clearColor];
tlabel.adjustsFontSizeToFitWidth=YES;
tlabel.textAlignment = NSTextAlignmentCenter;
self.navigationItem.titleView=tlabel;

Swift Version

self.title = "Your Title Text"
let tlabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
tlabel.text = self.title
tlabel.textColor = UIColor.white
tlabel.font = UIFont.systemFont(ofSize: 30, weight: .bold)
tlabel.backgroundColor = UIColor.clear
tlabel.adjustsFontSizeToFitWidth = true
tlabel.textAlignment = .center
self.navigationItem.titleView = tlabel

Hope it works for you.Thanks

Solution 2

Swift version of Accepted Answer + putting the label text on center :

Swift 2.3:

    self.title = "Your TiTle Text"
    let tlabel = UILabel(frame: CGRectMake(0, 0, 200, 40))
    tlabel.text = self.title
    tlabel.textColor = UIColor.whiteColor()
    tlabel.font = UIFont.boldSystemFontOfSize(17) //UIFont(name: "Helvetica", size: 17.0)
    tlabel.backgroundColor = UIColor.clearColor()
    tlabel.adjustsFontSizeToFitWidth = true
    tlabel.textAlignment = .Center
    self.navigationItem.titleView = tlabel

And Swift 3 :

    self.title = "Your TiTle Text"
    let frame = CGRect(x: 0, y: 0, width: 200, height: 40)
    let tlabel = UILabel(frame: frame)
    tlabel.text = self.title
    tlabel.textColor = UIColor.white
    tlabel.font = UIFont.boldSystemFont(ofSize: 17) //UIFont(name: "Helvetica", size: 17.0)
    tlabel.backgroundColor = UIColor.clear
    tlabel.adjustsFontSizeToFitWidth = true
    tlabel.textAlignment = .center
    self.navigationItem.titleView = tlabel

Solution 3

In case you have a view added into titleView, and you want to resize the view, you can use this code (Swift 3):

self.translatesAutoresizingMaskIntoConstraints = false
self.layoutIfNeeded()
self.sizeToFit()
self.translatesAutoresizingMaskIntoConstraints = true

Solution 4

This works for me

Objective C

[UILabel appearanceWhenContainedInInstancesOfClasses:@[[UINavigationBar class]]].adjustsFontSizeToFitWidth = YES;

Swift Version

UILabel.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).adjustsFontSizeToFitWidth = true

Solution 5

None of the above solutions seam to work reliably for me. However I found a solution by using different elements of the provides answers, its in Swift 2 and is really elegant as it does not require any custom code each time you change the label, it just uses property observers on the title.

Note that in my case, I had a back button on the left side of the navigation bar, which putted the text out of the center of the screen, to fix this I am using attributed text and the tailIndent. All comments/info in the code below :

class VCHowToTopic : UIViewController {


    //add handlers so that any manipulation of the title is caught and transferred to the custom drawn UILabel
    override var title : String? {
        set {
            super.title = newValue
            configureTitleView()
        }
        get {
            return super.title
        }
    }

    //MARK: - lifecycle


    func configureTitleView() {
        //some large number that makes the navigationbar schrink down our view when added
        let someVeryLargeNumber = CGFloat(4096)
        //create our label
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: someVeryLargeNumber, height: someVeryLargeNumber))
        //0 means unlimited number of lines
        titleLabel.numberOfLines = 0
        //define style of the text (we will be using attributed text)
        let style = NSMutableParagraphStyle()
        style.alignment = .Center
        //top compensate for the backbutton which moves the centered text to the right side of the screen
        //we introduce a negative tail indent, the number of 56 has been experimentally defined and might
        //depend on the size of your custom back button (if you have one), mine is 22x22 px
        style.tailIndent = -56
        //create attributed text also with the right color
        let attrText = NSAttributedString(string: title!, attributes: [NSParagraphStyleAttributeName : style,
            NSForegroundColorAttributeName : UIColor.whiteColor()])
        //configure the label to use the attributed text
        titleLabel.attributedText = attrText
        //add it as the titleview
        navigationItem.titleView = titleLabel
    }


}
Share:
24,955
PhoenixDev
Author by

PhoenixDev

Bachelor CS Pakistan. In Germany for my Masters. Love to code. Wish to learn a lot more.

Updated on July 09, 2022

Comments

  • PhoenixDev
    PhoenixDev almost 2 years

    I have some views that show up in a navigation controller. Two of these views have a longer title for the navigation bar.

    The problem is that when the title is too long to fit, some characters are truncated and "..." is added.

    Is there any way I can tell the Navigation bar to re-size the title text automatically to fit?