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)
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)
结果如下: