Swift 5, Xcode 10.2
I want to display 2 lines of text in the UINavigationBar
, that's why I'm using a UILabel
:
@IBOutlet weak var navigationBar: UINavigationItem!
override func viewDidLoad() {
let labeltext = NSMutableAttributedString.init(string: "Text in line 1\n(Line 2)")
labeltext.setAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)],range: NSRange(location: labeltext.length-8, length: 8))
let label = UILabel()
label.backgroundColor = .clear
label.numberOfLines = 2
label.font = UIFont.boldSystemFont(ofSize: 17.0)
label.textAlignment = .center
label.textColor = .black
label.attributedText = labeltext
navigationBar.titleView = label
}
In portrait orientation it looks like this:
On smaller devices the text is cut off in landscape (it's fine on iPhone Xs Max and iPad):
I tried to extend UINavigationBar
as suggested here:
extension UINavigationBar {
open override func sizeThatFits(_ size: CGSize) -> CGSize {
let portraitSize = CGSize(width: UIScreen.main.bounds.width, height: 44)
return portraitSize
}
}
... but didn't change anything and print("Navigationbar height: \(navigationController!.navigationBar.frame.height)")
always prints "44", no matter what the orientation it is and what device I use (even on iPhone X).
Adding an observer as suggested here also didn't help.
How do I fix this to display 2 lines of code while not breaking it for bigger devices/devices with a notch?