Search code examples
swiftuinavigationcontrolleruinavigationitem

manually setting titleView of navigationItem is not alligned vertically


I am using this func inside a UIViewController extension to add a title that adjusts font to fit width.

extesion UIViewController {
    func setTitleDifferentSizes(title: String){
        self.title = title
        guard let navigationBarHeight: CGFloat = 
self.navigationController?.navigationBar.frame.height else{
            return
        }

        let tlabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 
        200.0, height: navigationBarHeight))
        tlabel.text = self.title
        tlabel.textColor = UIColor.white
        tlabel.font = font24
        tlabel.backgroundColor = UIColor.clear
        tlabel.adjustsFontSizeToFitWidth = true
        self.navigationItem.titleView = tlabel
    }
}

I took this solution from this SO question and changed it a little bit: How to resize Title in a navigation bar dynamically

Now the issue I have is that the text of the title is not aligned vertically to the other navigation bar items, as you can see in the images, I show one where I just setup the title without using the above method, and the text there cannot fit but it is aligned properly, and the other image is using the method above where the text fits but it is not aligned.

enter image description here

enter image description here


Solution

  • try this:-

       func setTitleDifferentSizes(title: String){
        self.title = title
        guard let navigationBarHeight: CGFloat =
            self.navigationController?.navigationBar.frame.height else{
                return
        }
        let attributedString = NSMutableAttributedString(string: title)
    
         let myAttribute = [ NSForegroundColorAttributeName: UIColor.white ,NSFontAttributeName: font24]
    
        attributedString.addAttributes(myAttribute, range: NSRange(location: 0, length: attributedString.string.characters.count))
    
        attributedString.addAttributes([NSBaselineOffsetAttributeName:6.0], range:         NSRange(location: 0, length: title.characters.count)
        )
    
        let tlabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width:
            200.0, height: navigationBarHeight))
        tlabel.attributedText = attributedString
        tlabel.backgroundColor = UIColor.clear
        tlabel.adjustsFontSizeToFitWidth = true
        tlabel.minimumScaleFactor = 0.2
        tlabel.textAlignment = .center
        self.navigationItem.titleView = tlabel
    }
    

    if you want to adjust the position of text please change the float value of NSBaselineOffsetAttributeName to set the vertical alignment.