Подтвердить что ты не робот

Как установить многострочный большой заголовок в панели навигации? (Новая функция iOS 11)

Я в процессе добавления большого заголовка на панели навигации в одном из приложений. Проблема в том, что заголовок немного длинный, поэтому мне потребуется добавить две строки в большом заголовке. Как добавить большой заголовок с двумя строками на панели навигации?

Это не по умолчанию заголовок панели навигации! Это большой заголовок, который представлен в iOS 11. Поэтому не забудьте добавить предложения, учитывая большой заголовок. Спасибо

enter image description here

4b9b3361

Ответ 1

Исходя из ответа @krunal, это работает для меня:

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
                })
            }
        }
    }
}

В UIViewController:

override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "This is a multiline title"
    setupNavigationMultilineTitle()
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    setupNavigationMultilineTitle()
}

И для установки шрифта и цвета на большом заголовке:

navigation.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: .red, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 30)]

Ответ 2

Получите навигационные элементы и найдите UILabel.

Попробуйте это и посмотрите:

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
         }
     }
}

Вот результат:

введите описание изображения здесь

Ответ 3

Swift 5.X

func setMultilineNavigationBar(topText:  String, bottomText : String) {
     let topTxt = NSLocalizedString(topText, comment: "")
     let bottomTxt = NSLocalizedString(bottomText, comment: "")

     let titleParameters = [NSAttributedString.Key.foregroundColor : UIColor.white,
                               NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .semibold)]
     let subtitleParameters = [NSAttributedString.Key.foregroundColor : UIColor.white,
                                  NSAttributedString.Key.font : UIFont.systemFont(ofSize: 13, weight: .regular)]

     let title:NSMutableAttributedString = NSMutableAttributedString(string: topTxt, attributes: titleParameters)
     let subtitle:NSAttributedString = NSAttributedString(string: bottomTxt, attributes: subtitleParameters)

     title.append(NSAttributedString(string: "\n"))
     title.append(subtitle)

     let size = title.size()

     let width = size.width
     guard let height = navigationController?.navigationBar.frame.size.height else {return}

      let titleLabel = UILabel(frame: CGRect.init(x: 0, y: 0, width: width, height: height))
      titleLabel.attributedText = title
      titleLabel.numberOfLines = 0
      titleLabel.textAlignment = .center
      self.navigationItem.titleView = titleLabel 
    }

Это работает нормально для меня. Надеюсь, эта функция поможет вам.

Удачного кодирования :)

Ответ 4

Swift 4: многострочный, хотя предложение короткое

title = "You're \nWelcome"

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
         }
     }
}

Proof

Ответ 5

Здесь вы можете добавить многострочную UILabel в NavigationTitle Вы можете сделать это с помощью некоторой настройки в вашем коде и поместить UILabel в self.navigationItem.titleView

    let label = UILabel()
    label.backgroundColor = .clear
    label.numberOfLines = 2
    label.font = UIFont(name: "Montserrat-Regular", size: 16.0)!
    label.textAlignment = .center
    label.textColor = .white
    label.text = "FIFA" + " \n " + "Europe 2018-2019"  
    self.navigationItem.titleView = label

Ура хорошего дня.

enter image description here

Ответ 6

Чтобы установить многострочный большой заголовок в панели навигации, выполните следующие действия:

Шаг 1: Добавьте свой заголовок в панель навигации через StoryBoard.

Шаг 2: Перейдите в файл ViewController и добавьте следующую строку в метод viewDidLoad()

self.navigationController?.navigationBar.prefersLargeTitles = true