My navigation bar's large title is too wide. How to fix that?

前端 未结 3 788
天命终不由人
天命终不由人 2021-02-15 09:07

I am using navigation controller, and I\'ve set to true its navigation bar\'s prefersLargeTitle property. Everything works fine, but when the text of my title becom

3条回答
  •  悲哀的现实
    2021-02-15 10:03

    This is the workaround that I found

    override func viewDidLoad() {
      super.viewDidLoad()
    
      title = yourTitle
      adjustLargeTitleSize()
    }
    
    extension UIViewController {
      func adjustLargeTitleSize() {
        guard let title = title, #available(iOS 11.0, *) else { return }
    
        let maxWidth = UIScreen.main.bounds.size.width - 60
        var fontSize = UIFont.preferredFont(forTextStyle: .largeTitle).pointSize
        var width = title.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize)]).width
    
        while width > maxWidth {
          fontSize -= 1
          width = title.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize)]).width
        }
    
        navigationController?.navigationBar.largeTitleTextAttributes =
            [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: fontSize)
        ]
      }
    }
    

提交回复
热议问题