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

时间:2017-12-20 08:01:16

标签: ios swift uilabel uinavigationbar large-title

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

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

enter image description here

8 个答案:

答案 0 :(得分:12)

获取导航项子视图并从中查找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
         }
     }
}

结果如下:

enter image description here

答案 1 :(得分:12)

基于@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 :(得分:1)

当有后退按钮时,换行解决方案似乎有问题。因此,我没有使行折线,而是使标签自动调整了字体。

func setupLargeTitleAutoAdjustFont() {
    guard let navigationBar = navigationController?.navigationBar else {
        return
    }
    // recursively find the label
    func findLabel(in view: UIView) -> UILabel? {
        if view.subviews.count > 0 {
            for subview in view.subviews {
                if let label = findLabel(in: subview) {
                    return label
                }
            }
        }
        return view as? UILabel
    }

    if let label = findLabel(in: navigationBar) {
        if label.text == self.title {
            label.adjustsFontSizeToFitWidth = true
            label.minimumScaleFactor = 0.7
        }
    }
}

然后需要在viewDidLayoutSubviews()中调用它以确保可以找到标签,并且我们只需要调用一次即可:

private lazy var setupLargeTitleLabelOnce: Void = {[unowned self] in
    if #available(iOS 11.0, *) {
        self.setupLargeTitleAutoAdjustFont()
    }
}()

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let _ = setupLargeTitleLabelOnce
}

如果此控制器有任何navigationController pop事件,则需要在viewDidAppear()中再次调用它。我还没有找到更好的解决方案-从弹出事件返回时,标签字体有一些小变化:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if #available(iOS 11.0, *) {
        setupLargeTitleAutoAdjustFont()
    }
}

答案 3 :(得分:0)

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 :(得分:0)

快捷键4 :即使句子很短,也还是多行

<div *ngSwitch="JSon.Type">
    <div *ngSwitchCase ="input">
        ...
    </div>
    <div *ngSwitchCase ="radio">
        ...
    </div>
</div>

Proof

答案 5 :(得分:0)

(编辑 7/13:我注意到这个解决方案不支持 scrollView,所以现在我在研究)

我在 Swift5 上找到了一个完美的解决方案

但是对不起我的英语不好,因为我是日本人??学生。

In case of 2 lines In case of 3 lines

首先在viewDidLoad中正常设置largeTitle的导航设置

//Set largeTitle
navigationItem.largeTitleDisplayMode = .automatic
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationBar.largeTitleTextAttributes = [.font: UIFont.systemFont(ofSize: (fontSize + margin) * numberOfLines)]//ex) fontSize=26, margin=5, numberOfLines=2
        
//Set title
title = "multiple large\ntitle is working!"

此解决方案最重要的一点是 largeTitleTextAttributes 处的字体大小等于实际字体大小(+margin)乘以行数。

Description image

因为,navigationBar 属性的默认规范可能能够只显示 1 行 largeTitle。

虽然,不知何故,我确实注意到在直接设置标签设置(导航栏子视图的子视图的标签)的情况下,它可以在导航栏属性的情况下在 1 行中显示任意数量的行< /strong>。

所以,我们应该在导航栏属性中设置大字体,并在标签(导航栏子视图的子视图)中设置小字体,并考虑边距。

像这样直接在 viewDidAppear 中设置标签:

//Find label
navigationController?.navigationBar.subviews.forEach({ subview in
        subview.subviews.forEach { subsubview in
        guard let label: UILabel = subsubview as? UILabel else { return }
        //Label settings on direct.
        label.text = title
        label.font = UIFont.systemFont(ofSize: fontSize)
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        label.sizeToFit()
    }
})

因此,简而言之,最小代码处的解决方案是这样给出的:

import UIKit

class ViewController: UIViewController {
    
    private let fontSize: CGFloat = 26, margin: CGFloat = 5
    private let numberOfLines: CGFloat = 2

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpNavigation()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        setMultipleLargeTitle()
    }
    private func setUpNavigation() {
        //Set largeTitle
        navigationItem.largeTitleDisplayMode = .automatic
        navigationController?.navigationBar.prefersLargeTitles = true
        navigationController?.navigationBar.largeTitleTextAttributes = [.font: UIFont.systemFont(ofSize: (fontSize + margin) * numberOfLines)]
        
        //Set title
        title = "multiple large\ntitle is working!"
    }
    private func setMultipleLargeTitle() {
        //Find label
        navigationController?.navigationBar.subviews.forEach({ subview in
            subview.subviews.forEach { subsubview in
                guard let label: UILabel = subsubview as? UILabel else { return }
                //Label settings on direct.
                label.text = title
                label.font = UIFont.systemFont(ofSize: fontSize)
                label.numberOfLines = 0
                label.lineBreakMode = .byWordWrapping
                label.sizeToFit()
            }
        })
    }
}

感谢阅读:)

答案 6 :(得分:-1)

在这里您可以在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

答案 7 :(得分:-5)

要在导航栏中设置多行大标题,请执行以下操作:

第1步:通过StoryBoard将标题添加到导航栏。

第2步:转到ViewController文件并在下面添加以下行 viewDidLoad()方法

self.navigationController?.navigationBar.prefersLargeTitles = true