如何在导航栏中设置多行大标题?(iOS 11的新功能)

Jig*_*kar 14 uinavigationbar uilabel ios swift large-title

我正在其中一个应用程序中的导航栏中添加大标题.问题是标题有点长,所以我需要在大标题中添加两行.如何在导航栏中添加两行大标题

这不是关于默认导航栏标题!这是关于iOS 11中引入的大标题.因此,请务必考虑大型标题来添加建议.谢谢

在此输入图像描述

小智 14

根据@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
                })
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在UIViewController中:

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

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    setupNavigationMultilineTitle()
}
Run Code Online (Sandbox Code Playgroud)

并在大标题上设置字体和颜色:

navigation.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: .red, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 30)]
Run Code Online (Sandbox Code Playgroud)

  • 该解决方案似乎不适用于带有 Xcode 11 的 iOS 13。 (4认同)

Kru*_*nal 13

获取导航项子视图并从中查找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
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述

  • 当我们没有后退按钮时,这很好用.你用后退按钮试试了吗? (11认同)
  • 我同意Jigar.我有一个后退按钮,这是行不通的.当我从左侧稍微滑动页面(好像要回去)时,它会工作,但然后让它反弹回原位. (2认同)