How to resize Title in a navigation bar dynamically

前端 未结 9 1905
慢半拍i
慢半拍i 2020-12-03 01:24

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

相关标签:
9条回答
  • 2020-12-03 01:55

    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
    
    0 讨论(0)
  • 2020-12-03 01:57

    you need to customize the navigation bar title view with uilabel and provide adjust font size..

        [self.navigationItem setTitleView:<"Include any UI View subclass">];
    
    0 讨论(0)
  • 2020-12-03 02:05

    Swift 4 and iOS 13

    Adding this so my future self can find it. Views added to titleView for some reason don't like to automatically resize themselves. So you have to do it manually.

    Example

    (navigationItem.titleView as? UILabel)?.text = "A longer string..." // label not resized and text is cut off
    

    Solution

    navigationItem.titleView?.translatesAutoresizingMaskIntoConstraints = false
    navigationItem.titleView?.setNeedsLayout()
    navigationItem.titleView?.layoutIfNeeded()
    navigationItem.titleView?.translatesAutoresizingMaskIntoConstraints = true
    

    Thanks to @Paolo Musolino for leading me here.

    0 讨论(0)
  • 2020-12-03 02:12

    You can create a UILabel as UINavigationItem's titleView and set it's adjustsFontSizeToFitWidth to true.

    class MyViewController: UIViewController {
        override var title: String? {
            didSet {
                (self.navigationItem.titleView as? UILabel)?.text = self.title
            }
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
    
            self.navigationItem.titleView = UILabel().apply {
                $0.font = .boldSystemFont(ofSize: 18)
                $0.minimumScaleFactor = 0.5
                $0.adjustsFontSizeToFitWidth = true
                $0.text = self.title
            }
        }
    }
    

    Easy to use:

    myViewController.title = "This is a long title, but don’t worry."
    

    The apply closure in the above code is a trick, in order to make the programming experience better. There is also a with closure. Recommend to everyone.

    protocol ScopeFunc {}
    
    extension ScopeFunc {
        @inline(__always) func apply(_ block: (Self) -> ()) -> Self {
            block(self)
            return self
        }
    
        @inline(__always) func with<R>(_ block: (Self) -> R) -> R {
            return block(self)
        }
    }
    
    extension NSObject: ScopeFunc {}
    
    0 讨论(0)
  • 2020-12-03 02:14

    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

    0 讨论(0)
  • 2020-12-03 02:14

    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
        }
    
    
    }
    
    0 讨论(0)
提交回复
热议问题