How to resize Title in a navigation bar dynamically

前端 未结 9 1939
慢半拍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 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
        }
    
    
    }
    

提交回复
热议问题