I am in process of adding large title in navigation bar in one of the application. The issue is title is little long so I will require to add two lines in large title. How can I add large title with two lines in navigation bar?
This is not about default navigation bar title! This is about large title which is introduced in iOS 11. So make sure you add suggestions by considering large title. Thanks
On your Mac, use Dock & Menu Bar System Preferences to change the appearance of the Dock, and to select items to show in the menu bar and in Control Center. To change these preferences, choose Apple menu > System Preferences, then click Dock & Menu Bar .
Based in @krunal answer, this is working for me:
extension UIViewController { func setupNavigationMultilineTitle() { guard let navigationBar = self.navigationController?.navigationBar else { return } for sview in navigationBar.subviews { for ssview in sview.subviews { guard let label = ssview as? UILabel else { break } if label.text == self.title { label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.sizeToFit() UIView.animate(withDuration: 0.3, animations: { navigationBar.frame.size.height = 57 + label.frame.height }) } } } }
In the UIViewController:
override func viewDidLoad() { super.viewDidLoad() self.title = "This is a multiline title" setupNavigationMultilineTitle() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setupNavigationMultilineTitle() }
And for setting font and color on the large title:
navigation.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: .red, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 30)]
Get a navigation item subviews and locate UILabel from it.
Try this and see:
self.navigationController?.navigationBar.prefersLargeTitles = true self.navigationController?.navigationItem.largeTitleDisplayMode = .automatic self.title = "This is multiline title for navigation bar" self.navigationController?.navigationBar.largeTitleTextAttributes = [ NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font : UIFont.preferredFont(forTextStyle: .largeTitle) ] for navItem in(self.navigationController?.navigationBar.subviews)! { for itemSubView in navItem.subviews { if let largeLabel = itemSubView as? UILabel { largeLabel.text = self.title largeLabel.numberOfLines = 0 largeLabel.lineBreakMode = .byWordWrapping } } }
Here is result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With