(编辑 7/13:我注意到这个解决方案不支持 scrollView,所以现在我正在研究)
我在Swift5上找到了一个完美的解决方案
但对不起我的英语不好,因为我是日本人??学生。
In case of 2 linesIn 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 处的字体大小等于实际字体大小(+边距)乘以行数。
Description image
因为,navigationBar 属性的默认规范可能只能显示1 行 largeTitle。
尽管不知何故,我确实注意到,在直接使用标签设置(导航栏子视图的子视图的标签)的情况下,在导航栏属性的情况下,它可以在 1 行中显示任意数量的行。
所以,我们应该在导航栏属性中设置大字体,在标签(导航栏的子视图的子视图)中设置小字体,并考虑到边距。
像这样直接在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()
}
})
}
}
感谢您的阅读:)