Customize the navigation bar by adding two labels instead of a name in Swift

I am trying to add two labels in the place where the title is displayed in the navigation bar, but I am trying my best to do it. It would be very nice if I could achieve this with the help of the storyboard, but, as I see it, I can not do it.

As I understand it, I need to use navigationItem, but I do not know how to do it. If anyone has any example or someone can explain to me more specifically how to do this, it would be great.

And I have to mention that I'm completely new to Obj-C, so any help should be in Swift.

+8
source share
2 answers

I'm not sure that you can do this from the storyboard, but if you want to add two header labels, you can do the following in the viewDidLoad () method of the view controller for which you want to use two headers:

if let navigationBar = self.navigationController?.navigationBar { let firstFrame = CGRect(x: 0, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height) let secondFrame = CGRect(x: navigationBar.frame.width/2, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height) let firstLabel = UILabel(frame: firstFrame) firstLabel.text = "First" let secondLabel = UILabel(frame: secondFrame) secondLabel.text = "Second" navigationBar.addSubview(firstLabel) navigationBar.addSubview(secondLabel) } 

This way you can add as many subzones as you want in the navigation bar

+25
source

Here is an implementation that uses the stack view instead, which also gives you some versatility with label layout:

 class ViewController: UIViewController { lazy var titleStackView: UIStackView = { let titleLabel = UILabel() titleLabel.textAlignment = .center titleLabel.text = "Title" let subtitleLabel = UILabel() subtitleLabel.textAlignment = .center subtitleLabel.text = "Subtitle" let stackView = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel]) stackView.axis = .vertical return stackView }() override func viewDidLoad() { super.viewDidLoad() navigationItem.titleView = titleStackView } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if view.traitCollection.horizontalSizeClass == .compact { titleStackView.axis = .vertical titleStackView.spacing = UIStackView.spacingUseDefault } else { titleStackView.axis = .horizontal titleStackView.spacing = 20.0 } } } 

Demonstrates using a stack view to create a custom navigation item's title view

0
source

All Articles