9

我有一个视图控制器,我需要在导航栏上显示多行标题。为此,我编写了这样的协议 -

import UIKit

protocol CustomNavigationBar {
    func setupNavigationMultilineTitle(titleText: String, prefersLargeTitles: Bool, largeTitleDisplayMode: UINavigationItem.LargeTitleDisplayMode)
}

然后扩展它-

extension CustomNavigationBar where Self : UIViewController {

    func setupNavigationMultilineTitle(titleText: String, prefersLargeTitles: Bool = true, largeTitleDisplayMode: UINavigationItem.LargeTitleDisplayMode = .automatic ) {

        self.navigationController?.navigationBar.prefersLargeTitles = prefersLargeTitles
        self.navigationController?.navigationItem.largeTitleDisplayMode = largeTitleDisplayMode
        self.navigationController?.navigationBar.largeTitleTextAttributes = [
            NSAttributedString.Key.foregroundColor: UIColor.black,
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18, weight: .semibold)
        ]
        self.title = titleText

        if let navBarSubViews = self.navigationController?.navigationBar.subviews {
            for navItem in navBarSubViews {
                for itemSubView in navItem.subviews {
                    if let largeLabel = itemSubView as? UILabel {
                        largeLabel.text = self.title
                        largeLabel.numberOfLines = 0
                        largeLabel.lineBreakMode = .byWordWrapping
                        largeLabel.sizeToFit()
                    }
                }
            }
        }
    }
}

在我的视图控制器中,我符合这个协议,在 viewDidAppear 方法中,我调用 setupNavigationMultilineTitle 方法如下 -

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.setupNavigationMultilineTitle(titleText: "This is created for testing This is created for testing This is created for testing This is created for testing This is created for testing")
}

**

这适用于运行低于 iOS13 的 iPhone。

**

在此处输入图像描述

**

但是,在运行高于 iOS 13 的 iPhone 上,它只显示一行然后被截断。

**

在此处输入图像描述

iOS13的UINavigationBar有变化吗?我研究并发现了一些关于背景颜色的信息,但与使用 prefersLargeTitles 和 largeTitleDisplayMode 的多行标题无关。

有人可以帮我在 iOS13 上安装这个吗?

谢谢!!

4

0 回答 0