我的导航栏的大标题太宽了.如何解决?

Tig*_*yan 7 uinavigationbar navigationcontroller ios swift

我正在使用导航控制器,我设置为真正的导航栏的prefersLargeTitle属性.一切都很好,但是当我的标题文字变得太大时,它就不适合空间.在这里看起来如何:

在此输入图像描述

有可能以某种方式使标题(当导航栏的prefersLargeTitle属性设置为true)动态调整其字体大小,如果是这样,如何实现?

Sou*_*ter 23

所有你需要的是:

UILabel.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).adjustsFontSizeToFitWidth = true
Run Code Online (Sandbox Code Playgroud)

还可在 iOS 15 上使用 SwiftUI。


vic*_*ava 18

这是我找到的解决方法

override func viewDidLoad() {
  super.viewDidLoad()

  title = yourTitle
  adjustLargeTitleSize()
}

extension UIViewController {
  func adjustLargeTitleSize() {
    guard let title = title, #available(iOS 11.0, *) else { return }

    let maxWidth = UIScreen.main.bounds.size.width - 60
    var fontSize = UIFont.preferredFont(forTextStyle: .largeTitle).pointSize
    var width = title.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize)]).width

    while width > maxWidth {
      fontSize -= 1
      width = title.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize)]).width
    }

    navigationController?.navigationBar.largeTitleTextAttributes =
        [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: fontSize)
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这很棒!我唯一要做的更改是用以下内容替换前面的行(前面的Swift 3语法): .navigationBar.largeTitleTextAttributes = titleAttributes}`这将保留标题的原始属性,同时仅修改字体大小。最后,根据他们的设置,可能需要使用`guard let title = self.navigationItem.title`。 (2认同)